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

The following examples show how to use com.github.dockerjava.api.model.Network. 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: AbstractDockerBasedEnvironment.java    From hawkular-apm with Apache License 2.0 6 votes vote down vote up
/**
 * Create network which is used as default in docker-compose.yml
 * This should be run before {@link DockerComposeExecutor#run(TestEnvironment)}
 */
@Override
public void createNetwork() {
    removeNetwork();

    String apmNetwork = apmBindAddress.substring(0, apmBindAddress.lastIndexOf(".")) + ".0/24";

    log.info(String.format("Creating network %s:", apmNetwork));

    Network.Ipam ipam = new Network.Ipam()
            .withConfig(new Network.Ipam.Config()
                    .withSubnet(apmNetwork)
                    .withGateway(apmBindAddress));

    CreateNetworkResponse createNetworkResponse = dockerClient.createNetworkCmd()
            .withName(Constants.HOST_ADDED_TO_ETC_HOSTS)
            .withIpam(ipam)
            .exec();

    try {
        network = dockerClient.inspectNetworkCmd().withNetworkId(createNetworkResponse.getId()).exec();
    } catch (DockerException ex) {
        log.severe(String.format("Could not create network: %s", createNetworkResponse));
        throw new EnvironmentException("Could not create network: " + createNetworkResponse, ex);
    }
}
 
Example #2
Source File: InspectNetworkCmdIT.java    From docker-java with Apache License 2.0 6 votes vote down vote up
@Test
public void inspectNetwork() throws DockerException {
    assumeNotSwarm("no network in swarm", dockerRule);

    List<Network> networks = dockerRule.getClient().listNetworksCmd().exec();

    Network expected = findNetwork(networks, "bridge");

    Network network = dockerRule.getClient().inspectNetworkCmd().withNetworkId(expected.getId()).exec();

    assertThat(network.getName(), equalTo(expected.getName()));
    assertThat(network.getScope(), equalTo(expected.getScope()));
    assertThat(network.getDriver(), equalTo(expected.getDriver()));
    assertThat(network.getIpam().getConfig().get(0).getSubnet(), equalTo(expected.getIpam().getConfig().get(0).getSubnet()));
    assertThat(network.getIpam().getDriver(), equalTo(expected.getIpam().getDriver()));
}
 
Example #3
Source File: DisconnectFromNetworkCmdIT.java    From docker-java with Apache License 2.0 6 votes vote down vote up
@Test
public void forceDisconnectFromNetwork() throws InterruptedException {
    assumeNotSwarm("no network in swarm", dockerRule);

    CreateNetworkResponse network = dockerRule.getClient().createNetworkCmd().withName("testNetwork2" + dockerRule.getKind()).exec();

    CreateContainerResponse container = dockerRule.getClient().createContainerCmd("busybox")
            .withHostConfig(newHostConfig()
                    .withNetworkMode("testNetwork2" + dockerRule.getKind()))
            .withCmd("sleep", "9999")
            .exec();

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

    dockerRule.getClient().disconnectFromNetworkCmd()
            .withNetworkId(network.getId())
            .withContainerId(container.getId())
            .withForce(true)
            .exec();

    Network updatedNetwork = dockerRule.getClient().inspectNetworkCmd().withNetworkId(network.getId()).exec();
    assertFalse(updatedNetwork.getContainers().containsKey(container.getId()));
}
 
Example #4
Source File: UpdateSwarmServiceIT.java    From docker-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testUpdateServiceReplicate() throws Exception {
    DockerClient dockerClient = startSwarm();
    //create network
    String networkId = dockerClient.createNetworkCmd().withName("networkname").withDriver("overlay")
            .withIpam(new Network.Ipam().withDriver("default")).exec().getId();
    TaskSpec taskSpec = new TaskSpec().withContainerSpec(
            new ContainerSpec().withImage("busybox").withArgs(Arrays.asList("sleep", "3600")));
    ServiceSpec serviceSpec = new ServiceSpec()
            .withMode(new ServiceModeConfig().withReplicated(new ServiceReplicatedModeOptions().withReplicas(1)))
            .withTaskTemplate(taskSpec)
            .withNetworks(Lists.newArrayList(new NetworkAttachmentConfig().withTarget(networkId)))
            .withName("worker");
    String serviceId = dockerClient.createServiceCmd(serviceSpec).exec().getId();
    await().untilAsserted(() -> {
        List<Service> services = dockerClient.listServicesCmd().withIdFilter(Arrays.asList(serviceId)).exec();
        assertThat(services.size(), is(1));
        Service service = services.get(0);
        ServiceSpec updateServiceSpec = service.getSpec()
            .withMode(new ServiceModeConfig().withReplicated(new ServiceReplicatedModeOptions().withReplicas(2)));
        dockerClient.updateServiceCmd(service.getId(), updateServiceSpec).withVersion(service.getVersion().getIndex()).exec();
        //verify the replicate
        Service updateService = dockerClient.listServicesCmd().withIdFilter(Arrays.asList(serviceId)).exec().get(0);
        assertThat(updateService.getSpec().getMode().getReplicated().getReplicas(), is(2L));
    });
}
 
Example #5
Source File: RemoveNetworkCmdIT.java    From docker-java with Apache License 2.0 6 votes vote down vote up
@Test
public void removeNetwork() throws DockerException {
    assumeNotSwarm("Swarm has no network", dockerRule);

    CreateNetworkResponse network = dockerRule.getClient().createNetworkCmd()
            .withName("test-network")
            .exec();

    LOG.info("Removing network: {}", network.getId());
    dockerRule.getClient().removeNetworkCmd(network.getId()).exec();

    List<Network> networks = dockerRule.getClient().listNetworksCmd().exec();

    Matcher matcher = not(hasItem(hasField("id", startsWith(network.getId()))));
    assertThat(networks, matcher);

}
 
Example #6
Source File: CreateNetworkCmdIT.java    From docker-java with Apache License 2.0 6 votes vote down vote up
@Test
public void createNetworkWithIpamConfig() throws DockerException {
    assumeNotSwarm("no network in swarm", dockerRule);

    String networkName = "networkIpam" + dockerRule.getKind();
    String subnet = "10.67." + (79 + getFactoryType().ordinal()) + ".0/24";

    Network.Ipam ipam = new Network.Ipam().withConfig(new Network.Ipam.Config().withSubnet(subnet));
    CreateNetworkResponse createNetworkResponse = dockerRule.getClient().createNetworkCmd().withName(networkName).withIpam(ipam).exec();

    assertNotNull(createNetworkResponse.getId());

    Network network = dockerRule.getClient().inspectNetworkCmd().withNetworkId(createNetworkResponse.getId()).exec();
    assertEquals(network.getName(), networkName);
    assertEquals("bridge", network.getDriver());
    assertEquals(subnet, network.getIpam().getConfig().iterator().next().getSubnet());
}
 
Example #7
Source File: NetworkLiveTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void whenInspectingNetwork_thenSizeMustBeGreaterThanZero() {

    // when
    String networkName = "bridge";
    Network network = dockerClient.inspectNetworkCmd().withNetworkId(networkName).exec();

    // then
    MatcherAssert.assertThat(network.getName(), is(networkName));
}
 
Example #8
Source File: ContainerUtil.java    From presto with Apache License 2.0 5 votes vote down vote up
public static void removeNetworks(DockerClient dockerClient, Function<ListNetworksCmd, ListNetworksCmd> filter)
{
    ListNetworksCmd listNetworksCmd = filter.apply(dockerClient.listNetworksCmd());
    List<Network> networks = listNetworksCmd.exec();
    for (Network network : networks) {
        dockerClient.removeNetworkCmd(network.getId())
                .exec();
    }
}
 
Example #9
Source File: NetworkLiveTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
@Ignore("temporarily")
public void whenListingNetworks_thenSizeMustBeGreaterThanZero() {

    // when
    List<Network> networks = dockerClient.listNetworksCmd().exec();

    // then
    assertThat(networks.size(), is(greaterThan(0)));
}
 
Example #10
Source File: InspectNetworkCmdExec.java    From docker-java with Apache License 2.0 5 votes vote down vote up
@Override
protected Network execute(InspectNetworkCmd command) {
    WebTarget webResource = getBaseResource().path("/networks/{id}").resolveTemplate("id", command.getNetworkId());

    LOGGER.trace("GET: {}", webResource);
    return webResource.request().accept(MediaType.APPLICATION_JSON).get(new TypeReference<Network>() {
    });
}
 
Example #11
Source File: ListNetworksCmdExec.java    From docker-java with Apache License 2.0 5 votes vote down vote up
@Override
protected List<Network> execute(ListNetworksCmd command) {
    WebTarget webTarget = getBaseResource().path("/networks");

    if (command.getFilters() != null && !command.getFilters().isEmpty()) {
        webTarget = webTarget.queryParam("filters", FiltersEncoder.jsonEncode(command.getFilters()));
    }

    LOGGER.trace("GET: {}", webTarget);

    return webTarget.request().accept(MediaType.APPLICATION_JSON).get(new TypeReference<List<Network>>() {
    });
}
 
Example #12
Source File: CreateNetworkCmdIT.java    From docker-java with Apache License 2.0 5 votes vote down vote up
@Test
public void createNetworkWithLabel() throws DockerException {
    assumeNotSwarm("no network in swarm?", dockerRule);
    assumeThat("API version should be >= 1.21", dockerRule, isGreaterOrEqual(VERSION_1_21));

    String networkName = "createNetworkWithLabel" + dockerRule.getKind();
    Map<String, String> labels = new HashMap<>();
    labels.put("com.example.usage" + dockerRule.getKind(), "test");
    CreateNetworkResponse createNetworkResponse = dockerRule.getClient().createNetworkCmd().withName(networkName).withLabels(labels).exec();
    assertNotNull(createNetworkResponse.getId());
    Network network = dockerRule.getClient().inspectNetworkCmd().withNetworkId(createNetworkResponse.getId()).exec();
    assertEquals(network.getLabels(), labels);
}
 
Example #13
Source File: CreateNetworkCmdIT.java    From docker-java with Apache License 2.0 5 votes vote down vote up
@Test
public void createAttachableNetwork() throws DockerException {
    assumeThat("API version should be > 1.24", dockerRule, isGreaterOrEqual(VERSION_1_25));

    String networkName = "createAttachableNetwork" + dockerRule.getKind();
    CreateNetworkResponse createNetworkResponse = dockerRule.getClient().createNetworkCmd()
            .withName(networkName)
            .withAttachable(true)
            .exec();
    assertNotNull(createNetworkResponse.getId());
    Network network = dockerRule.getClient().inspectNetworkCmd().withNetworkId(createNetworkResponse.getId()).exec();
    assertThat(network, notNullValue());
    assertTrue(network.isAttachable());
}
 
Example #14
Source File: CreateNetworkCmdIT.java    From docker-java with Apache License 2.0 5 votes vote down vote up
@Test
public void createNetwork() throws DockerException {
    assumeNotSwarm("no network in swarm", dockerRule);

    String networkName = "createNetwork" + dockerRule.getKind();

    CreateNetworkResponse createNetworkResponse = dockerRule.getClient().createNetworkCmd().withName(networkName).exec();

    assertNotNull(createNetworkResponse.getId());

    Network network = dockerRule.getClient().inspectNetworkCmd().withNetworkId(createNetworkResponse.getId()).exec();
    assertThat(network.getName(), is(networkName));
    assertThat(network.getDriver(), is("bridge"));
}
 
Example #15
Source File: CreateContainerCmdIT.java    From docker-java with Apache License 2.0 5 votes vote down vote up
@Test
public void createContainerWithCustomIp() throws DockerException {
    String containerName1 = "containerCustomIplink_" + dockerRule.getKind();
    String networkName = "customIpNet" + dockerRule.getKind();
    String subnetPrefix = getFactoryType().getSubnetPrefix() + "101";

    CreateNetworkResponse createNetworkResponse = dockerRule.getClient().createNetworkCmd()
            .withIpam(new Network.Ipam()
                    .withConfig(new Network.Ipam.Config()
                            .withSubnet(subnetPrefix + ".0/24")))
            .withDriver("bridge")
            .withName(networkName)
            .exec();

    assertNotNull(createNetworkResponse.getId());

    CreateContainerResponse container = dockerRule.getClient().createContainerCmd(DEFAULT_IMAGE)
            .withHostConfig(newHostConfig()
                    .withNetworkMode(networkName))
            .withCmd("sleep", "9999")
            .withName(containerName1)
            .withIpv4Address(subnetPrefix + ".100")
            .exec();

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

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

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

    ContainerNetwork customIpNet = inspectContainerResponse.getNetworkSettings().getNetworks().get(networkName);
    assertNotNull(customIpNet);
    assertThat(customIpNet.getGateway(), is(subnetPrefix + ".1"));
    assertThat(customIpNet.getIpAddress(), is(subnetPrefix + ".100"));
}
 
Example #16
Source File: ListNetworksCmdIT.java    From docker-java with Apache License 2.0 5 votes vote down vote up
@Test
public void listNetworks() throws DockerException {
    assumeNotSwarm("Swarm has no network", dockerRule);

    List<Network> networks = dockerRule.getClient().listNetworksCmd().exec();

    Network network = TestUtils.findNetwork(networks, "bridge");

    assertThat(network.getName(), equalTo("bridge"));
    assertThat(network.getScope(), equalTo("local"));
    assertThat(network.getDriver(), equalTo("bridge"));
    assertThat(network.getIpam().getDriver(), equalTo("default"));
}
 
Example #17
Source File: TestUtils.java    From docker-java with Apache License 2.0 5 votes vote down vote up
public static Network findNetwork(List<Network> networks, String name) {

        for (Network network : networks) {
            if (StringUtils.equals(network.getName(), name)) {
                return network;
            }
        }

        throw new AssertionError("No network found.");
    }
 
Example #18
Source File: DockerClientProviderStrategy.java    From testcontainers-java with MIT License 5 votes vote down vote up
@VisibleForTesting
static String resolveDockerHostIpAddress(DockerClient client, URI dockerHost) {
    switch (dockerHost.getScheme()) {
        case "http":
        case "https":
        case "tcp":
            return dockerHost.getHost();
        case "unix":
        case "npipe":
            if (DockerClientConfigUtils.IN_A_CONTAINER) {
                return client.inspectNetworkCmd()
                    .withNetworkId("bridge")
                    .exec()
                    .getIpam()
                    .getConfig()
                    .stream()
                    .filter(it -> it.getGateway() != null)
                    .findAny()
                    .map(Network.Ipam.Config::getGateway)
                    .orElseGet(() -> {
                        return DockerClientConfigUtils.getDefaultGateway().orElse("localhost");
                    });
            }
            return "localhost";
        default:
            return null;
    }
}
 
Example #19
Source File: ConnectToNetworkCmdIT.java    From docker-java with Apache License 2.0 4 votes vote down vote up
@Test
public void connectToNetwork() throws InterruptedException {
    assumeNotSwarm("no network in swarm", dockerRule);
    String networkName = "connectToNetwork" + dockerRule.getKind();

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

    CreateNetworkResponse network = dockerRule.getClient().createNetworkCmd().withName(networkName).exec();

    dockerRule.getClient().connectToNetworkCmd().withNetworkId(network.getId()).withContainerId(container.getId()).exec();

    Network updatedNetwork = dockerRule.getClient().inspectNetworkCmd().withNetworkId(network.getId()).exec();

    assertTrue(updatedNetwork.getContainers().containsKey(container.getId()));

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

    assertNotNull(inspectContainerResponse.getNetworkSettings().getNetworks().get(networkName));
}
 
Example #20
Source File: ConnectToNetworkCmdIT.java    From docker-java with Apache License 2.0 4 votes vote down vote up
@Test
public void connectToNetworkWithContainerNetwork() throws InterruptedException {
    assumeNotSwarm("no network in swarm", dockerRule);

    final String subnetPrefix = getFactoryType().getSubnetPrefix() + "100";
    final String networkName = "ContainerWithNetwork" + dockerRule.getKind();
    final String containerIp = subnetPrefix + ".100";

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

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

    try {
        dockerRule.getClient().removeNetworkCmd(networkName).exec();
    } catch (DockerException ignore) {
    }

    CreateNetworkResponse network = dockerRule.getClient().createNetworkCmd()
        .withName(networkName)
        .withIpam(new Network.Ipam()
            .withConfig(new Network.Ipam.Config()
                .withSubnet(subnetPrefix + ".0/24")))
        .exec();

    dockerRule.getClient().connectToNetworkCmd()
        .withNetworkId(network.getId())
        .withContainerId(container.getId())
        .withContainerNetwork(new ContainerNetwork()
            .withAliases("aliasName" + dockerRule.getKind())
            .withIpamConfig(new ContainerNetwork.Ipam()
                .withIpv4Address(containerIp)))
        .exec();

    Network updatedNetwork = dockerRule.getClient().inspectNetworkCmd().withNetworkId(network.getId()).exec();

    Network.ContainerNetworkConfig containerNetworkConfig = updatedNetwork.getContainers().get(container.getId());
    assertNotNull(containerNetworkConfig);
    assertThat(containerNetworkConfig.getIpv4Address(), is(containerIp + "/24"));

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

    ContainerNetwork testNetwork = inspectContainerResponse.getNetworkSettings().getNetworks().get(networkName);
    assertNotNull(testNetwork);
    assertThat(testNetwork.getAliases(), hasItem("aliasName" + dockerRule.getKind()));
    assertThat(testNetwork.getGateway(), is(subnetPrefix + ".1"));
    assertThat(testNetwork.getIpAddress(), is(containerIp));
}
 
Example #21
Source File: DisconnectFromNetworkCmdIT.java    From docker-java with Apache License 2.0 4 votes vote down vote up
@Test
public void disconnectFromNetwork() throws InterruptedException {
    assumeNotSwarm("no network in swarm", dockerRule);

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

    CreateNetworkResponse network = dockerRule.getClient().createNetworkCmd().withName("disconnectNetwork" + dockerRule.getKind()).exec();

    dockerRule.getClient().connectToNetworkCmd().withNetworkId(network.getId()).withContainerId(container.getId()).exec();

    Network updatedNetwork = dockerRule.getClient().inspectNetworkCmd().withNetworkId(network.getId()).exec();

    assertTrue(updatedNetwork.getContainers().containsKey(container.getId()));

    dockerRule.getClient().disconnectFromNetworkCmd().withNetworkId(network.getId()).withContainerId(container.getId()).exec();

    updatedNetwork = dockerRule.getClient().inspectNetworkCmd().withNetworkId(network.getId()).exec();

    assertFalse(updatedNetwork.getContainers().containsKey(container.getId()));
}
 
Example #22
Source File: CreateServiceCmdExecIT.java    From docker-java with Apache License 2.0 4 votes vote down vote up
@Test
public void testCreateServiceWithNetworks() {
    String networkId = dockerClient.createNetworkCmd().withName("networkname")
            .withDriver("overlay")
            .withIpam(new Network.Ipam()
                    .withDriver("default"))
            .exec().getId();
    ServiceSpec spec = new ServiceSpec()
            .withName(SERVICE_NAME)
            .withTaskTemplate(new TaskSpec()
                    .withForceUpdate(0)
                    .withRuntime("container")
                    .withContainerSpec(new ContainerSpec()
                            .withImage("busybox"))
            )
            .withNetworks(Lists.newArrayList(
                    new NetworkAttachmentConfig()
                            .withTarget(networkId)
                            .withAliases(Lists.<String>newArrayList("alias1", "alias2"))
            ))
            .withLabels(ImmutableMap.of("com.docker.java.usage", "SwarmServiceIT"))
            .withMode(new ServiceModeConfig().withReplicated(
                    new ServiceReplicatedModeOptions()
                            .withReplicas(1)
            )).withEndpointSpec(new EndpointSpec()
                    .withMode(EndpointResolutionMode.VIP)
                    .withPorts(Lists.<PortConfig>newArrayList(new PortConfig()
                            .withPublishMode(PortConfig.PublishMode.host)
                            .withPublishedPort(22)
                            .withProtocol(PortConfigProtocol.TCP)
                    )));

    dockerClient.createServiceCmd(spec).exec();

    List<Service> services = dockerClient.listServicesCmd()
            .withNameFilter(Lists.newArrayList(SERVICE_NAME))
            .exec();

    assertThat(services, hasSize(1));

    assertThat(services.get(0).getSpec(), is(spec));

    dockerClient.removeServiceCmd(SERVICE_NAME).exec();
}
 
Example #23
Source File: CreateNetworkCmd.java    From docker-java with Apache License 2.0 4 votes vote down vote up
@CheckForNull
Network.Ipam getIpam();
 
Example #24
Source File: InpectNetworkCmdImpl.java    From docker-java with Apache License 2.0 4 votes vote down vote up
public InpectNetworkCmdImpl(DockerCmdSyncExec<InspectNetworkCmd, Network> exec) {
    super(exec);
}
 
Example #25
Source File: CreateNetworkCmdImpl.java    From docker-java with Apache License 2.0 4 votes vote down vote up
@Override
public Network.Ipam getIpam() {
    return ipam;
}
 
Example #26
Source File: BaseDockerComposeTest.java    From testcontainers-java with MIT License 4 votes vote down vote up
private List<String> findAllNetworks() {
  return DockerClientFactory.instance().client().listNetworksCmd().exec().stream()
    .map(Network::getName)
    .sorted()
    .collect(Collectors.toList());
}
 
Example #27
Source File: InspectNetworkCmd.java    From docker-java with Apache License 2.0 2 votes vote down vote up
/**
 * @throws NotFoundException
 *             No such network
 */
@Override
Network exec() throws NotFoundException;