com.amazonaws.services.ec2.model.Vpc Java Examples

The following examples show how to use com.amazonaws.services.ec2.model.Vpc. 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: AwsNetworkService.java    From cloudbreak with Apache License 2.0 6 votes vote down vote up
public String findNonOverLappingCIDR(AuthenticatedContext ac, CloudStack stack) {
    AwsNetworkView awsNetworkView = new AwsNetworkView(stack.getNetwork());
    String region = ac.getCloudContext().getLocation().getRegion().value();
    AmazonEC2Client ec2Client = awsClient.createAccess(new AwsCredentialView(ac.getCloudCredential()), region);

    DescribeVpcsRequest vpcRequest = new DescribeVpcsRequest().withVpcIds(awsNetworkView.getExistingVpc());
    Vpc vpc = ec2Client.describeVpcs(vpcRequest).getVpcs().get(0);
    String vpcCidr = vpc.getCidrBlock();
    LOGGER.debug("Subnet cidr is empty, find a non-overlapping subnet for VPC cidr: {}", vpcCidr);

    DescribeSubnetsRequest request = new DescribeSubnetsRequest().withFilters(new Filter("vpc-id", singletonList(awsNetworkView.getExistingVpc())));
    List<Subnet> awsSubnets = ec2Client.describeSubnets(request).getSubnets();
    List<String> subnetCidrs = awsSubnets.stream().map(Subnet::getCidrBlock).collect(Collectors.toList());
    LOGGER.debug("The selected VPCs: {}, has the following subnets: {}", vpc.getVpcId(), String.join(",", subnetCidrs));

    return calculateSubnet(ac.getCloudContext().getName(), vpc, subnetCidrs);
}
 
Example #2
Source File: AwsNetworkServiceTest.java    From cloudbreak with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetVpcCidrs() {
    String cidr1 = "1.2.3.0/24";
    String cidr2 = "10.0.0.0/8";
    AuthenticatedContext authenticatedContext = mock(AuthenticatedContext.class);
    CloudContext cloudContext = mock(CloudContext.class);
    CloudStack cloudStack = mock(CloudStack.class);
    AmazonEC2Client ec2Client = mock(AmazonEC2Client.class);
    when(authenticatedContext.getCloudContext()).thenReturn(cloudContext);
    when(cloudStack.getNetwork()).thenReturn(new Network(new Subnet(null), Map.of("vpcId", "vpc-123")));
    when(cloudContext.getLocation()).thenReturn(Location.location(Region.region("eu-west1")));
    when(awsClient.createAccess(any(AwsCredentialView.class), anyString())).thenReturn(ec2Client);
    when(ec2Client.describeVpcs(any(DescribeVpcsRequest.class)))
            .thenReturn(new DescribeVpcsResult().withVpcs(new Vpc()
                    .withCidrBlockAssociationSet(new VpcCidrBlockAssociation().withCidrBlock(cidr1), new VpcCidrBlockAssociation().withCidrBlock(cidr2))));

    List<String> vpcCidrs = underTest.getVpcCidrs(authenticatedContext, cloudStack);

    assertTrue(vpcCidrs.contains(cidr1));
    assertTrue(vpcCidrs.contains(cidr2));
}
 
Example #3
Source File: AwsNetworkService.java    From cloudbreak with Apache License 2.0 6 votes vote down vote up
private String calculateSubnet(String stackName, Vpc vpc, Iterable<String> subnetCidrs) {
    SubnetInfo vpcInfo = new SubnetUtils(vpc.getCidrBlock()).getInfo();
    String[] cidrParts = vpcInfo.getCidrSignature().split("/");
    int netmask = Integer.parseInt(cidrParts[cidrParts.length - 1]);
    int netmaskBits = CIDR_PREFIX - netmask;
    if (netmaskBits <= 0) {
        throw new CloudConnectorException("The selected VPC has to be in a bigger CIDR range than /24");
    }
    int numberOfSubnets = Double.valueOf(Math.pow(2, netmaskBits)).intValue();
    int targetSubnet = 0;
    if (stackName != null) {
        byte[] b = stackName.getBytes(Charset.forName("UTF-8"));
        for (byte ascii : b) {
            targetSubnet += ascii;
        }
    }
    targetSubnet = Long.valueOf(targetSubnet % numberOfSubnets).intValue();
    String cidr = getSubnetCidrInRange(vpc, subnetCidrs, targetSubnet, numberOfSubnets);
    if (cidr == null) {
        cidr = getSubnetCidrInRange(vpc, subnetCidrs, 0, targetSubnet);
    }
    if (cidr == null) {
        throw new CloudConnectorException("Cannot find non-overlapping CIDR range");
    }
    return cidr;
}
 
Example #4
Source File: AwsNetworkService.java    From cloudbreak with Apache License 2.0 6 votes vote down vote up
public List<String> getVpcCidrs(AuthenticatedContext ac, CloudStack stack) {
    AwsNetworkView awsNetworkView = new AwsNetworkView(stack.getNetwork());
    if (awsNetworkView.isExistingVPC()) {
        String region = ac.getCloudContext().getLocation().getRegion().value();
        AmazonEC2Client ec2Client = awsClient.createAccess(new AwsCredentialView(ac.getCloudCredential()), region);

        DescribeVpcsRequest vpcRequest = new DescribeVpcsRequest().withVpcIds(awsNetworkView.getExistingVpc());
        Vpc vpc = ec2Client.describeVpcs(vpcRequest).getVpcs().get(0);
        List<String> cidrBlockAssociationSet = vpc.getCidrBlockAssociationSet().stream()
                .map(VpcCidrBlockAssociation::getCidrBlock)
                .collect(Collectors.toList());
        LOGGER.info("VPC associated CIDR blocks: [{}]", cidrBlockAssociationSet);
        return cidrBlockAssociationSet;
    } else {
        return Collections.emptyList();
    }
}
 
Example #5
Source File: AwsPlatformResources.java    From cloudbreak with Apache License 2.0 6 votes vote down vote up
private List<Subnet> getSubnets(AmazonEC2Client ec2Client, Vpc vpc) {
    List<Subnet> awsSubnets = new ArrayList<>();
    DescribeSubnetsResult describeSubnetsResult = null;
    boolean first = true;
    while (first || !isNullOrEmpty(describeSubnetsResult.getNextToken())) {
        LOGGER.debug("Describing subnets for VPC {}{}", vpc.getVpcId(), first ? "" : " (continuation)");
        first = false;
        DescribeSubnetsRequest describeSubnetsRequest = createSubnetsDescribeRequest(vpc, describeSubnetsResult == null
                ? null
                : describeSubnetsResult.getNextToken());
        describeSubnetsResult = ec2Client.describeSubnets(describeSubnetsRequest);
        awsSubnets.addAll(describeSubnetsResult.getSubnets());
        awsSubnets = awsSubnets.stream().filter(subnet -> !deniedAZs.contains(subnet.getAvailabilityZone()))
                .collect(Collectors.toList());
    }
    return awsSubnets;
}
 
Example #6
Source File: AwsPlatformResources.java    From cloudbreak with Apache License 2.0 6 votes vote down vote up
private Set<CloudNetwork> getCloudNetworks(AmazonEC2Client ec2Client,
        DescribeRouteTablesResult describeRouteTablesResult, DescribeVpcsResult describeVpcsResult) {

    Set<CloudNetwork> cloudNetworks = new HashSet<>();
    LOGGER.debug("Processing VPCs");
    for (Vpc vpc : describeVpcsResult.getVpcs()) {
        List<Subnet> awsSubnets = getSubnets(ec2Client, vpc);
        Set<CloudSubnet> subnets = convertAwsSubnetsToCloudSubnets(describeRouteTablesResult, awsSubnets);

        Map<String, Object> properties = prepareNetworkProperties(vpc);
        Optional<String> name = getName(vpc.getTags());
        if (name.isPresent()) {
            cloudNetworks.add(new CloudNetwork(name.get(), vpc.getVpcId(), subnets, properties));
        } else {
            cloudNetworks.add(new CloudNetwork(vpc.getVpcId(), vpc.getVpcId(), subnets, properties));
        }
    }
    return cloudNetworks;
}
 
Example #7
Source File: VpcTableProvider.java    From aws-athena-query-federation with Apache License 2.0 6 votes vote down vote up
/**
 * Maps a VPC into a row in our Apache Arrow response block(s).
 *
 * @param vpc The VPCs to map.
 * @param spiller The BlockSpiller to use when we want to write a matching row to the response.
 * @note The current implementation is rather naive in how it maps fields. It leverages a static
 * list of fields that we'd like to provide and then explicitly filters and converts each field.
 */
private void instanceToRow(Vpc vpc,
        BlockSpiller spiller)
{
    spiller.writeRows((Block block, int row) -> {
        boolean matched = true;

        matched &= block.offerValue("id", row, vpc.getVpcId());
        matched &= block.offerValue("cidr_block", row, vpc.getCidrBlock());
        matched &= block.offerValue("dhcp_opts", row, vpc.getDhcpOptionsId());
        matched &= block.offerValue("tenancy", row, vpc.getInstanceTenancy());
        matched &= block.offerValue("owner", row, vpc.getOwnerId());
        matched &= block.offerValue("state", row, vpc.getState());
        matched &= block.offerValue("is_default", row, vpc.getIsDefault());

        List<String> tags = vpc.getTags().stream()
                .map(next -> next.getKey() + ":" + next.getValue()).collect(Collectors.toList());
        matched &= block.offerComplexValue("tags", row, FieldResolver.DEFAULT, tags);

        return matched ? 1 : 0;
    });
}
 
Example #8
Source File: VpcTableProvider.java    From aws-athena-query-federation with Apache License 2.0 6 votes vote down vote up
/**
 * Calls DescribeVPCs on the AWS EC2 Client returning all VPCs that match the supplied predicate and attempting
 * to push down certain predicates (namely queries for specific VPCs) to EC2.
 *
 * @See TableProvider
 */
@Override
public void readWithConstraint(BlockSpiller spiller, ReadRecordsRequest recordsRequest, QueryStatusChecker queryStatusChecker)
{
    DescribeVpcsRequest request = new DescribeVpcsRequest();

    ValueSet idConstraint = recordsRequest.getConstraints().getSummary().get("id");
    if (idConstraint != null && idConstraint.isSingleValue()) {
        request.setVpcIds(Collections.singletonList(idConstraint.getSingleValue().toString()));
    }

    DescribeVpcsResult response = ec2.describeVpcs(request);
    for (Vpc vpc : response.getVpcs()) {
        instanceToRow(vpc, spiller);
    }
}
 
Example #9
Source File: VpcTableProviderTest.java    From aws-athena-query-federation with Apache License 2.0 6 votes vote down vote up
@Override
protected void setUpRead()
{
    when(mockEc2.describeVpcs(any(DescribeVpcsRequest.class))).thenAnswer((InvocationOnMock invocation) -> {
        DescribeVpcsRequest request = (DescribeVpcsRequest) invocation.getArguments()[0];

        assertEquals(getIdValue(), request.getVpcIds().get(0));
        DescribeVpcsResult mockResult = mock(DescribeVpcsResult.class);
        List<Vpc> values = new ArrayList<>();
        values.add(makeVpc(getIdValue()));
        values.add(makeVpc(getIdValue()));
        values.add(makeVpc("fake-id"));
        when(mockResult.getVpcs()).thenReturn(values);
        return mockResult;
    });
}
 
Example #10
Source File: Ec2NetworkTest.java    From aws-mock with MIT License 6 votes vote down vote up
/**
 * Test describing vpcs.
 */
@Test(timeout = TIMEOUT_LEVEL1)
public final void describeAllNetworksTest() {
    log.info("Start describing vpcs test");
    List<Vpc> vpcs = describeVpcs();

    Assert.assertNotNull("vpcs should not be null", vpcs);
    Assert.assertNotNull("vpc id should not be null", vpcs.get(0).getVpcId());
    log.info("Vpc Sizes " + vpcs.size());

    log.info("Start describing vpcs test");
    List<Subnet> subnets = getSubnets();

    Assert.assertNotNull("vpcs should not be null", subnets);
    Assert.assertNotNull("vpc id should not be null", subnets.get(0).getSubnetId());
    log.info("Subnets Sizes " + subnets.size());

    log.info("Start describing vpcs test");
    List<InternetGateway> internetGateways = getInternetGateways();

    Assert.assertNotNull("vpcs should not be null", internetGateways);
    Assert.assertNotNull("vpc id should not be null", internetGateways.get(0).getInternetGatewayId());
    log.info("Subnets Sizes " + internetGateways.size());

}
 
Example #11
Source File: Ec2NetworkTest.java    From aws-mock with MIT License 5 votes vote down vote up
/**
 * Test Authorize Security Group Ingress.
 */
@Test(timeout = TIMEOUT_LEVEL1)
public final void authorizeSecurityGroupIngressTest() {
    log.info("Start authorizeSecurityGroupIngressTest test");
    Vpc vpc = createVpc(MOCK_CIDR_BLOCK, PROPERTY_TENANCY);
    
    String securityGroupId = createSecurityGroup("test-sg", "groupDescription", vpc.getVpcId());

    Assert.assertNotNull("Security Group id id should not be null", securityGroupId);
    Assert.assertTrue("Security Group should be deleted", authorizeSecurityGroupIngress(securityGroupId, "TCP", 22, MOCK_CIDR_BLOCK));
    
}
 
Example #12
Source File: Ec2NetworkTest.java    From aws-mock with MIT License 5 votes vote down vote up
/**
 * Test describing vpcs.
 */
@Test(timeout = TIMEOUT_LEVEL1)
public final void describeVpcsTest() {
    log.info("Start describing vpcs test");
    createVpcTest();
    List<Vpc> vpcs = describeVpcs();

    Assert.assertNotNull("vpcs should not be null", vpcs);
    Assert.assertNotNull("vpc id should not be null", vpcs.get(0).getVpcId());
    
    Assert.assertTrue("Vpc Should be deleted", deleteVpc(vpcs.get(0).getVpcId()));
}
 
Example #13
Source File: Ec2NetworkTest.java    From aws-mock with MIT License 5 votes vote down vote up
/**
 * Test create vpcs.
 */
@Test(timeout = TIMEOUT_LEVEL1)
public final void createVpcTest() {
    log.info("Start describing vpcs test");

    Vpc vpc = createVpc(MOCK_CIDR_BLOCK, PROPERTY_TENANCY);

    Assert.assertNotNull("vpcs should not be null", vpc);
    Assert.assertNotNull("vpc id should not be null", vpc.getVpcId());
}
 
Example #14
Source File: Ec2NetworkTest.java    From aws-mock with MIT License 5 votes vote down vote up
/**
 * Delete create vpcs.
 */
@Test(timeout = TIMEOUT_LEVEL1)
public final void deleteVpcTest() {
    log.info("Start describing vpcs test");

    Vpc vpc = createVpc(MOCK_CIDR_BLOCK, PROPERTY_TENANCY);

    Assert.assertNotNull("vpcs should not be null", vpc);
    Assert.assertNotNull("vpc id should not be null", vpc.getVpcId());
    
    Assert.assertTrue("Vpc Should be deleted", deleteVpc(vpc.getVpcId()));
}
 
Example #15
Source File: Ec2NetworkTest.java    From aws-mock with MIT License 5 votes vote down vote up
/**
 * Test attach internet gateway.
 */
@Test(timeout = TIMEOUT_LEVEL1)
public final void attachInternetGatewayTest() {
    log.info("Attach internet gateway test");
    
    Vpc vpc = createVpc(MOCK_CIDR_BLOCK, PROPERTY_TENANCY);
    
    InternetGateway internetGateway = createInternetGateway();
    
    Assert.assertTrue("internet gateway should be attached to vpc", attachInternetGateway(internetGateway.getInternetGatewayId(), vpc.getVpcId()));
}
 
Example #16
Source File: Ec2NetworkTest.java    From aws-mock with MIT License 5 votes vote down vote up
/**
 * Test create route table.
 */
@Test(timeout = TIMEOUT_LEVEL1)
public final void createRouteTableTest() {
    log.info("Start create route table test");
    Vpc vpc = createVpc(MOCK_CIDR_BLOCK, PROPERTY_TENANCY);
    
    RouteTable routeTable = createRouteTable(vpc.getVpcId());
    
    Assert.assertNotNull("route table should not be null", routeTable);
    Assert.assertNotNull("route table id should not be null", routeTable.getRouteTableId());
}
 
Example #17
Source File: Ec2NetworkTest.java    From aws-mock with MIT License 5 votes vote down vote up
/**
 * Test Delete route table.
 */
@Test(timeout = TIMEOUT_LEVEL1)
public final void deleteRouteTableTest() {
    log.info("Start delete route table test");
    Vpc vpc = createVpc(MOCK_CIDR_BLOCK, PROPERTY_TENANCY);

    RouteTable routeTable = createRouteTable(vpc.getVpcId());

    Assert.assertNotNull("route table should not be null", routeTable);
    Assert.assertNotNull("route table id should not be null", routeTable.getRouteTableId());

    Assert.assertTrue("route table should be deleted", deleteRouteTable(routeTable.getRouteTableId()));
}
 
Example #18
Source File: Ec2NetworkTest.java    From aws-mock with MIT License 5 votes vote down vote up
/**
 * Test create Subnet.
 */
@Test(timeout = TIMEOUT_LEVEL1)
public final void createSubnetTest() {
    log.info("Start create Subnet test");
    Vpc vpc = createVpc(MOCK_CIDR_BLOCK, PROPERTY_TENANCY);
    
    Subnet subnet = createSubnet(MOCK_CIDR_BLOCK, vpc.getVpcId());

    Assert.assertNotNull("subnet should not be null", subnet);
    Assert.assertNotNull("subnet id should not be null", subnet.getSubnetId());
}
 
Example #19
Source File: Ec2NetworkTest.java    From aws-mock with MIT License 5 votes vote down vote up
/**
 * Test create Security Group.
 */
@Test(timeout = TIMEOUT_LEVEL1)
public final void createSecurityGroupTest() {
    log.info("Start create Security Group test");
    Vpc vpc = createVpc(MOCK_CIDR_BLOCK, PROPERTY_TENANCY);
    
    String securityGroupId = createSecurityGroup("test-sg", "groupDescription", vpc.getVpcId());

    Assert.assertNotNull("Security Group id should not be null", securityGroupId);
}
 
Example #20
Source File: BaseTest.java    From aws-mock with MIT License 5 votes vote down vote up
/**
 * Create VPC.
 *
 * @param cidrBlock the cidr block
 * @param instanceTenancy the instance tenancy
 * @return New vpc
 */
protected final Vpc createVpc(final String cidrBlock, final String instanceTenancy) {
    CreateVpcRequest req = new CreateVpcRequest();
    req.setCidrBlock(cidrBlock);
    req.setInstanceTenancy(instanceTenancy);
    CreateVpcResult result = amazonEC2Client.createVpc(req);
    return result.getVpc();
}
 
Example #21
Source File: Ec2NetworkTest.java    From aws-mock with MIT License 5 votes vote down vote up
/**
 * Test Authorize Security Group Egress.
 */
@Test(timeout = TIMEOUT_LEVEL1)
public final void authorizeSecurityGroupEgressTest() {
    log.info("Start authorizeSecurityGroupEgressTest test");
    Vpc vpc = createVpc(MOCK_CIDR_BLOCK, PROPERTY_TENANCY);
    
    String securityGroupId = createSecurityGroup("test-sg", "groupDescription", vpc.getVpcId());

    Assert.assertNotNull("Security Group id should not be null", securityGroupId);
    Assert.assertTrue("Security Group should be deleted", authorizeSecurityGroupEgress(securityGroupId, "TCP", 22, MOCK_CIDR_BLOCK));
    
}
 
Example #22
Source File: Ec2NetworkTest.java    From aws-mock with MIT License 5 votes vote down vote up
/**
 * Test delete Subnet.
 */
@Test(timeout = TIMEOUT_LEVEL1)
public final void deleteSubnetTest() {
    log.info("Start delete Subnet test");
    Vpc vpc = createVpc(MOCK_CIDR_BLOCK, PROPERTY_TENANCY);
    
    Subnet subnet = createSubnet(MOCK_CIDR_BLOCK, vpc.getVpcId());

    Assert.assertNotNull("subnet should not be null", subnet);
    Assert.assertNotNull("subnet id should not be null", subnet.getSubnetId());
    Assert.assertTrue("subnet should be deleted", deleteSubnet(subnet.getSubnetId()));
}
 
Example #23
Source File: BaseTest.java    From aws-mock with MIT License 5 votes vote down vote up
/**
 * Describe VPCs.
 *
 * @return List of vpcs
 */
protected final List<Vpc> describeVpcs() {
    DescribeVpcsRequest req = new DescribeVpcsRequest();
    DescribeVpcsResult result = amazonEC2Client.describeVpcs(req);
    List<Vpc> vpcs = result.getVpcs();
    return vpcs;
}
 
Example #24
Source File: Ec2NetworkTest.java    From aws-mock with MIT License 5 votes vote down vote up
/**
 * Test create Volumes.
 */
@Test(timeout = TIMEOUT_LEVEL1)
public final void createNetworkResourcesTest() {
    
    //Create VPCs
    for(int i =0 ; i < 2 ; i++)
    {
        createVpcTest(); 
    }
    
    List<Vpc> vpcs = describeVpcs();
    
    // Create Subnet
    for(Vpc vpc : vpcs) {
        
        for(int j=0; j<2; j++)
        {
            Subnet subnet = createSubnet(MOCK_CIDR_BLOCK, vpc.getVpcId());
            RouteTable routeTable = createRouteTable(vpc.getVpcId());
            InternetGateway internetGateway = createInternetGateway();

            createRoute(routeTable.getRouteTableId(), internetGateway.getInternetGatewayId(), MOCK_CIDR_BLOCK);
            
            attachInternetGateway(internetGateway.getInternetGatewayId(), vpc.getVpcId());
        }
    }
}
 
Example #25
Source File: Ec2NetworkTest.java    From aws-mock with MIT License 5 votes vote down vote up
/**
 * Test delete SecurityGroup.
 */
@Test(timeout = TIMEOUT_LEVEL1)
public final void deleteSecurityGroupTest() {
    log.info("Start delete SecurityGroup test");
    Vpc vpc = createVpc(MOCK_CIDR_BLOCK, PROPERTY_TENANCY);
    
    String securityGroupId = createSecurityGroup("test-sg", "groupDescription", vpc.getVpcId());

    Assert.assertNotNull("Security Group should not be null", securityGroupId);
    Assert.assertTrue("Security Group should be deleted", deleteSecurityGroup(securityGroupId));
}
 
Example #26
Source File: VpcTableProviderTest.java    From aws-athena-query-federation with Apache License 2.0 5 votes vote down vote up
private Vpc makeVpc(String id)
{
    Vpc vpc = new Vpc();
    vpc.withVpcId(id)
            .withCidrBlock("cidr_block")
            .withDhcpOptionsId("dhcp_opts")
            .withInstanceTenancy("tenancy")
            .withOwnerId("owner")
            .withState("state")
            .withIsDefault(true)
            .withTags(new Tag("key", "valye"));

    return vpc;
}
 
Example #27
Source File: AwsPlatformResources.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
private Map<String, Object> prepareNetworkProperties(Vpc vpc) {
    Map<String, Object> properties = new HashMap<>();
    properties.put("cidrBlock", vpc.getCidrBlock());
    properties.put("default", vpc.getIsDefault());
    properties.put("dhcpOptionsId", vpc.getDhcpOptionsId());
    properties.put("instanceTenancy", vpc.getInstanceTenancy());
    properties.put("state", vpc.getState());
    return properties;
}
 
Example #28
Source File: AwsNetworkService.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
private String getSubnetCidrInRange(Vpc vpc, Iterable<String> subnetCidrs, int start, int end) {
    SubnetInfo vpcInfo = new SubnetUtils(vpc.getCidrBlock()).getInfo();
    String lowProbe = incrementIp(vpcInfo.getLowAddress());
    String highProbe = new SubnetUtils(toSubnetCidr(lowProbe)).getInfo().getHighAddress();
    // start from the target subnet
    for (int i = 0; i < start - 1; i++) {
        lowProbe = incrementIp(lowProbe);
        highProbe = incrementIp(highProbe);
    }
    boolean foundProbe = false;
    for (int i = start; i < end; i++) {
        boolean overlapping = false;
        for (String subnetCidr : subnetCidrs) {
            SubnetInfo subnetInfo = new SubnetUtils(subnetCidr).getInfo();
            if (isInRange(lowProbe, subnetInfo) || isInRange(highProbe, subnetInfo)) {
                overlapping = true;
                break;
            }
        }
        if (overlapping) {
            lowProbe = incrementIp(lowProbe);
            highProbe = incrementIp(highProbe);
        } else {
            foundProbe = true;
            break;
        }
    }
    if (foundProbe && isInRange(highProbe, vpcInfo)) {
        String subnet = toSubnetCidr(lowProbe);
        LOGGER.debug("The following subnet cidr found: {} for VPC: {}", subnet, vpc.getVpcId());
        return subnet;
    } else {
        return null;
    }
}
 
Example #29
Source File: AwsNetworkConnector.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
@Override
public NetworkCidr getNetworkCidr(Network network, CloudCredential credential) {
    AwsCredentialView awsCredentialView = new AwsCredentialView(credential);
    AmazonEC2Client awsClientAccess = awsClient.createAccess(awsCredentialView, network.getStringParameter(AwsNetworkView.REGION));
    AwsNetworkView awsNetworkView = new AwsNetworkView(network);
    String existingVpc = awsNetworkView.getExistingVpc();
    DescribeVpcsResult describeVpcsResult = awsClientAccess.describeVpcs(new DescribeVpcsRequest().withVpcIds(existingVpc));
    List<String> vpcCidrs = new ArrayList<>();
    for (Vpc vpc : describeVpcsResult.getVpcs()) {
        if (vpc.getCidrBlockAssociationSet() != null) {
            LOGGER.info("The VPC {} has associated CIDR block so using the CIDR blocks in the VPC.", vpc.getVpcId());
            List<String> cidrs = vpc.getCidrBlockAssociationSet()
                    .stream()
                    .map(VpcCidrBlockAssociation::getCidrBlock)
                    .collect(Collectors.toList());
            LOGGER.info("The VPC {} CIDRs block are {}.", vpc.getVpcId(), cidrs);
            vpcCidrs.addAll(cidrs);
        } else {
            LOGGER.info("The VPC {} has no associated CIDR block so using the CIDR block in the VPC.", vpc.getVpcId());
            vpcCidrs.add(vpc.getCidrBlock());
        }
    }

    if (vpcCidrs.isEmpty()) {
        throw new BadRequestException("VPC cidr could not fetch from AWS: " + existingVpc);
    }
    if (vpcCidrs.size() > 1) {
        LOGGER.info("More than one vpc cidrs for VPC {}. We will use the first one: {}", existingVpc, vpcCidrs.get(0));
    }
    return new NetworkCidr(vpcCidrs.get(0), vpcCidrs);
}
 
Example #30
Source File: AwsNetworkServiceTest.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
@Test
public void testFindNonOverLappingCIDRWit24VpcEmptySubnet() {
    InstanceAuthentication instanceAuthentication = new InstanceAuthentication("sshkey", "", "cloudbreak");

    Group group1 = new Group("group1", InstanceGroupType.CORE, Collections.emptyList(), null, null,
            instanceAuthentication, instanceAuthentication.getLoginUserName(), instanceAuthentication.getPublicKey(), ROOT_VOLUME_SIZE, identity);
    Map<String, Object> networkParameters = new HashMap<>();
    networkParameters.put("vpcId", "vpc-12345678");
    networkParameters.put("internetGatewayId", "igw-12345678");
    Network network = new Network(new Subnet(null), networkParameters);
    CloudStack cloudStack = new CloudStack(singletonList(group1), network, null, emptyMap(), emptyMap(), null,
            instanceAuthentication, instanceAuthentication.getLoginUserName(), instanceAuthentication.getPublicKey(), null);
    AuthenticatedContext authenticatedContext = mock(AuthenticatedContext.class);
    CloudContext cloudContext = mock(CloudContext.class);
    Location location = mock(Location.class);
    Vpc vpc = mock(Vpc.class);
    DescribeVpcsResult describeVpcsResult = mock(DescribeVpcsResult.class);
    AmazonEC2Client ec2Client = mock(AmazonEC2Client.class);
    DescribeSubnetsResult subnetsResult = mock(DescribeSubnetsResult.class);

    when(authenticatedContext.getCloudContext()).thenReturn(cloudContext);
    when(cloudContext.getLocation()).thenReturn(location);
    when(location.getRegion()).thenReturn(Region.region("eu-west-1"));
    when(awsClient.createAccess(any(), any())).thenReturn(ec2Client);
    when(ec2Client.describeVpcs(any())).thenReturn(describeVpcsResult);
    when(describeVpcsResult.getVpcs()).thenReturn(singletonList(vpc));
    when(vpc.getCidrBlock()).thenReturn("10.0.0.0/24");
    when(ec2Client.describeSubnets(any())).thenReturn(subnetsResult);
    when(subnetsResult.getSubnets()).thenReturn(Collections.emptyList());

    thrown.expect(CloudConnectorException.class);
    thrown.expectMessage("The selected VPC has to be in a bigger CIDR range than /24");

    underTest.findNonOverLappingCIDR(authenticatedContext, cloudStack);
}