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

The following examples show how to use com.amazonaws.services.ec2.model.Subnet. 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: 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 #2
Source File: Ec2DaoImpl.java    From herd with Apache License 2.0 6 votes vote down vote up
/**
 * This implementation uses the DescribeAvailabilityZones API to get the list of AZs.
 */
@Override
public List<AvailabilityZone> getAvailabilityZonesForSubnetIds(Collection<Subnet> subnets, AwsParamsDto awsParamsDto)
{
    Set<String> zoneNames = new HashSet<>();
    for (Subnet subnet : subnets)
    {
        zoneNames.add(subnet.getAvailabilityZone());
    }

    AmazonEC2Client ec2Client = getEc2Client(awsParamsDto);
    DescribeAvailabilityZonesRequest describeAvailabilityZonesRequest = new DescribeAvailabilityZonesRequest();
    describeAvailabilityZonesRequest.setZoneNames(zoneNames);
    DescribeAvailabilityZonesResult describeAvailabilityZonesResult = ec2Operations.describeAvailabilityZones(ec2Client, describeAvailabilityZonesRequest);
    return describeAvailabilityZonesResult.getAvailabilityZones();
}
 
Example #3
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 #4
Source File: AwsPlatformResources.java    From cloudbreak with Apache License 2.0 6 votes vote down vote up
private Set<CloudSubnet> convertAwsSubnetsToCloudSubnets(DescribeRouteTablesResult describeRouteTablesResult, List<Subnet> awsSubnets) {
    Set<CloudSubnet> subnets = new HashSet<>();
    for (Subnet subnet : awsSubnets) {
        boolean hasInternetGateway = awsSubnetIgwExplorer.hasInternetGatewayOfSubnet(describeRouteTablesResult, subnet.getSubnetId());
        LOGGER.info("The subnet {} has internetGateway value is '{}'", subnet, hasInternetGateway);
        Optional<String> subnetName = getName(subnet.getTags());
        subnets.add(
                new CloudSubnet(
                        subnet.getSubnetId(),
                        subnetName.orElse(subnet.getSubnetId()),
                        subnet.getAvailabilityZone(),
                        subnet.getCidrBlock(),
                        !hasInternetGateway,
                        subnet.getMapPublicIpOnLaunch(),
                        hasInternetGateway,
                        PUBLIC)
        );
    }
    return subnets;
}
 
Example #5
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 #6
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 #7
Source File: AwsSetup.java    From cloudbreak with Apache License 2.0 6 votes vote down vote up
private void validateExistingSubnet(AwsNetworkView awsNetworkView, AmazonEC2 amazonEC2Client) {
    if (awsNetworkView.isExistingSubnet()) {
        DescribeSubnetsRequest describeSubnetsRequest = new DescribeSubnetsRequest();
        describeSubnetsRequest.withSubnetIds(awsNetworkView.getSubnetList());
        DescribeSubnetsResult describeSubnetsResult = amazonEC2Client.describeSubnets(describeSubnetsRequest);
        if (describeSubnetsResult.getSubnets().size() < awsNetworkView.getSubnetList().size()) {
            throw new CloudConnectorException(String.format(SUBNET_DOES_NOT_EXIST_MSG, awsNetworkView.getExistingSubnet()));
        } else {
            for (Subnet subnet : describeSubnetsResult.getSubnets()) {
                String vpcId = subnet.getVpcId();
                if (vpcId != null && !vpcId.equals(awsNetworkView.getExistingVpc())) {
                    throw new CloudConnectorException(String.format(SUBNETVPC_DOES_NOT_EXIST_MSG, awsNetworkView.getExistingSubnet(),
                            awsNetworkView.getExistingVpc()));
                }
            }
        }
    }
}
 
Example #8
Source File: AwsIaasGatewayScriptService.java    From primecloud-controller with GNU General Public License v2.0 6 votes vote down vote up
@Override
public boolean hasSubnets(String vpcId) throws AutoException {
    if (StringUtils.isEmpty(vpcId)) {
        log.info(platform.getPlatformName() + " にvpcIdが有りません");
        System.out.println("VPCID_EMPTY");
        return false;
    }

    DescribeSubnetsRequest request = new DescribeSubnetsRequest();
    request.withFilters(new Filter().withName("vpc-id").withValues(vpcId));
    DescribeSubnetsResult result = ec2Client.describeSubnets(request);
    List<Subnet> subnets = result.getSubnets();

    if (subnets.isEmpty()) {
        log.info(platform.getPlatformName() + " にサブネットが有りません");
        System.out.println("SUBNET_EMPTY");
        return false;
    }

    return true;
}
 
Example #9
Source File: EmrPricingHelper.java    From herd with Apache License 2.0 6 votes vote down vote up
/**
 * Updates the given definition with the given subnet and EMR pricing information.
 * <p/>
 * Sets the subnet with the given subnet ID. Removes any maxSearchPrice and onDemandThreshold that were set. Sets the spotPrice only if the given cluster
 * price is a spot.
 *
 * @param emrClusterDefinition the definition to update
 * @param bestEmrClusterSubnet the subnet to use
 * @param bestEmrClusterPrice the EMR pricing information for each instance
 */
private void updateInstanceDefinitionsWithBestPrice(EmrClusterDefinition emrClusterDefinition, Subnet bestEmrClusterSubnet,
    EmrClusterPriceDto bestEmrClusterPrice)
{
    emrClusterDefinition.setSubnetId(bestEmrClusterSubnet.getSubnetId());

    emrClusterDefinition.getInstanceDefinitions().getMasterInstances().setInstanceMaxSearchPrice(null);
    emrClusterDefinition.getInstanceDefinitions().getMasterInstances().setInstanceOnDemandThreshold(null);
    emrClusterDefinition.getInstanceDefinitions().getMasterInstances().setInstanceSpotPrice(getSpotBidPrice(bestEmrClusterPrice.getMasterPrice()));

    if (bestEmrClusterPrice.getCorePrice() != null)
    {
        emrClusterDefinition.getInstanceDefinitions().getCoreInstances().setInstanceMaxSearchPrice(null);
        emrClusterDefinition.getInstanceDefinitions().getCoreInstances().setInstanceOnDemandThreshold(null);
        emrClusterDefinition.getInstanceDefinitions().getCoreInstances().setInstanceSpotPrice(getSpotBidPrice(bestEmrClusterPrice.getCorePrice()));
    }
}
 
Example #10
Source File: EC2Communication.java    From development with Apache License 2.0 6 votes vote down vote up
/**
 * Checks whether exiting Subnet is present.
 * 
 * @param subnetString
 * @return <code>Subnet </code> if the matches one of the subnetString
 * 
 */
public Subnet resolveSubnet(String subnetString) throws APPlatformException {
    DescribeSubnetsRequest request = new DescribeSubnetsRequest();
    DescribeSubnetsResult result = getEC2().describeSubnets(
            request.withSubnetIds(subnetString));
    List<Subnet> subnets = result.getSubnets();
    if (!subnets.isEmpty()) {
        LOGGER.debug(" number of subnets found: " + subnets.size());
        for (Subnet subnet : subnets) {
            LOGGER.debug("return subnet with id " + subnet.getSubnetId());
            return subnet;
        }

    }
    throw new APPlatformException(
            Messages.getAll("error_invalid_subnet_id") + subnetString);

}
 
Example #11
Source File: InventoryUtilTest.java    From pacbot with Apache License 2.0 6 votes vote down vote up
/**
 * Fetch subnets test.
 *
 * @throws Exception the exception
 */
@SuppressWarnings("static-access")
@Test
public void fetchSubnetsTest() throws Exception {
    
    mockStatic(AmazonEC2ClientBuilder.class);
    AmazonEC2 ec2Client = PowerMockito.mock(AmazonEC2.class);
    AmazonEC2ClientBuilder amazonEC2ClientBuilder = PowerMockito.mock(AmazonEC2ClientBuilder.class);
    AWSStaticCredentialsProvider awsStaticCredentialsProvider = PowerMockito.mock(AWSStaticCredentialsProvider.class);
    PowerMockito.whenNew(AWSStaticCredentialsProvider.class).withAnyArguments().thenReturn(awsStaticCredentialsProvider);
    when(amazonEC2ClientBuilder.standard()).thenReturn(amazonEC2ClientBuilder);
    when(amazonEC2ClientBuilder.withCredentials(anyObject())).thenReturn(amazonEC2ClientBuilder);
    when(amazonEC2ClientBuilder.withRegion(anyString())).thenReturn(amazonEC2ClientBuilder);
    when(amazonEC2ClientBuilder.build()).thenReturn(ec2Client);
    
    DescribeSubnetsResult describeSubnetsResult = new DescribeSubnetsResult();
    List<Subnet> subnets = new ArrayList<>();
    subnets.add(new Subnet());
    describeSubnetsResult.setSubnets(subnets);
    when(ec2Client.describeSubnets()).thenReturn(describeSubnetsResult);
    assertThat(inventoryUtil.fetchSubnets(new BasicSessionCredentials("awsAccessKey", "awsSecretKey", "sessionToken"), 
            "skipRegions", "account","accountName").size(), is(1));
}
 
Example #12
Source File: InventoryUtil.java    From pacbot with Apache License 2.0 6 votes vote down vote up
/**
 * Fetch subnets.
 *
 * @param temporaryCredentials the temporary credentials
 * @param skipRegions the skip regions
 * @param accountId the accountId
 * @param accountName the account name
 * @return the map
 */
public static Map<String,List<Subnet>> fetchSubnets(BasicSessionCredentials temporaryCredentials, String skipRegions,String accountId,String accountName) {
	Map<String,List<Subnet>> subnets = new LinkedHashMap<>();
	AmazonEC2 ec2Client ;
	String expPrefix = InventoryConstants.ERROR_PREFIX_CODE+accountId + "\",\"Message\": \"Exception in fetching info for resource in specific region\" ,\"type\": \"Subnet\" , \"region\":\"" ;
	for(Region region : RegionUtils.getRegions()){
		try{
			if(!skipRegions.contains(region.getName())){
				ec2Client = AmazonEC2ClientBuilder.standard().withCredentials(new AWSStaticCredentialsProvider(temporaryCredentials)).withRegion(region.getName()).build();
				DescribeSubnetsResult rslt = ec2Client.describeSubnets();
				List<Subnet> subnetsTemp =rslt.getSubnets();
				if(! subnetsTemp.isEmpty() ){
					log.debug(InventoryConstants.ACCOUNT + accountId +" Type : Subnet "+region.getName() + " >> "+subnetsTemp.size());
					subnets.put(accountId+delimiter+accountName+delimiter+region.getName(),subnetsTemp);
				}

			}
		}catch(Exception e){
			log.warn(expPrefix+ region.getName()+InventoryConstants.ERROR_CAUSE +e.getMessage()+"\"}");
			ErrorManageUtil.uploadError(accountId,region.getName(),"subnet",e.getMessage());
		}
	}

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

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

    DescribeSubnetsResult response = ec2.describeSubnets(request);
    for (Subnet subnet : response.getSubnets()) {
        instanceToRow(subnet, spiller);
    }
}
 
Example #14
Source File: SubnetTableProviderTest.java    From aws-athena-query-federation with Apache License 2.0 6 votes vote down vote up
@Override
protected void setUpRead()
{
    when(mockEc2.describeSubnets(any(DescribeSubnetsRequest.class))).thenAnswer((InvocationOnMock invocation) -> {
        DescribeSubnetsRequest request = (DescribeSubnetsRequest) invocation.getArguments()[0];

        assertEquals(getIdValue(), request.getSubnetIds().get(0));
        DescribeSubnetsResult mockResult = mock(DescribeSubnetsResult.class);
        List<Subnet> values = new ArrayList<>();
        values.add(makeSubnet(getIdValue()));
        values.add(makeSubnet(getIdValue()));
        values.add(makeSubnet("fake-id"));
        when(mockResult.getSubnets()).thenReturn(values);

        return mockResult;
    });
}
 
Example #15
Source File: SubnetTableProvider.java    From aws-athena-query-federation with Apache License 2.0 6 votes vote down vote up
/**
 * Maps an EC2 Subnet into a row in our Apache Arrow response block(s).
 *
 * @param subnet The EC2 Subnet 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(Subnet subnet,
        BlockSpiller spiller)
{
    spiller.writeRows((Block block, int row) -> {
        boolean matched = true;

        matched &= block.offerValue("id", row, subnet.getSubnetId());
        matched &= block.offerValue("availability_zone", row, subnet.getAvailabilityZone());
        matched &= block.offerValue("available_ip_count", row, subnet.getAvailableIpAddressCount());
        matched &= block.offerValue("cidr_block", row, subnet.getCidrBlock());
        matched &= block.offerValue("default_for_az", row, subnet.getDefaultForAz());
        matched &= block.offerValue("map_public_ip", row, subnet.getMapPublicIpOnLaunch());
        matched &= block.offerValue("owner", row, subnet.getOwnerId());
        matched &= block.offerValue("state", row, subnet.getState());
        matched &= block.offerValue("vpc", row, subnet.getVpcId());
        matched &= block.offerValue("vpc", row, subnet.getVpcId());

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

        return matched ? 1 : 0;
    });
}
 
Example #16
Source File: EditInstanceAws.java    From primecloud-controller with GNU General Public License v2.0 5 votes vote down vote up
private Subnet getSubnet(Long userNo, Long platformNo, String cidrBlock) {
    List<Subnet> subnets = awsDescribeService.getSubnets(userNo, platformNo);
    for (Subnet subnet : subnets) {
        if (subnet.getCidrBlock().equals(cidrBlock)) {
            return subnet;
        }
    }

    return null;
}
 
Example #17
Source File: AwsDescribeServiceImpl.java    From primecloud-controller with GNU General Public License v2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public List<Subnet> getSubnets(Long userNo, Long platformNo) {
    // VPCかどうかのチェック
    PlatformAws platformAws = platformAwsDao.read(platformNo);
    if (BooleanUtils.isNotTrue(platformAws.getVpc())) {
        // 非VPCの場合、サブネットはない
        return new ArrayList<Subnet>();
    }

    // サブネットを取得
    AwsProcessClient awsProcessClient = awsProcessClientFactory.createAwsProcessClient(userNo, platformNo);
    DescribeSubnetsRequest request = new DescribeSubnetsRequest();
    request.withFilters(new Filter().withName("vpc-id").withValues(platformAws.getVpcId()));
    DescribeSubnetsResult result = awsProcessClient.getEc2Client().describeSubnets(request);
    List<Subnet> subnets = result.getSubnets();

    // プラットフォームにサブネットが指定されている場合、そのサブネットのみに制限する
    if (StringUtils.isNotEmpty(awsProcessClient.getPlatformAws().getSubnetId())) {
        List<String> subnetIds = new ArrayList<String>();
        for (String subnetId : StringUtils.split(awsProcessClient.getPlatformAws().getSubnetId(), ",")) {
            subnetIds.add(subnetId.trim());
        }

        List<Subnet> subnets2 = new ArrayList<Subnet>();
        for (Subnet subnet : subnets) {
            if (subnetIds.contains(subnet.getSubnetId())) {
                subnets2.add(subnet);
            }
        }
        subnets = subnets2;
    }

    // ソート
    Collections.sort(subnets, Comparators.COMPARATOR_SUBNET);

    return subnets;
}
 
Example #18
Source File: EditLoadBalancer.java    From primecloud-controller with GNU General Public License v2.0 5 votes vote down vote up
/**
 * サブネットの取得
 *
 * @param userNo ユーザ番号
 * @param platformNo プラットフォーム番号
 * @param vpcId vpcId
 * @param cidrBlocks cidrBlockのリスト
 * @return List<Subnet> cidrBlockに合致するサブネットのみ取得
 */
private List<Subnet> getSubnet(Long userNo, Long platformNo, String vpcId, List<String> cidrBlocks) {
    List<Subnet> subnets = new ArrayList<Subnet>();
    if (cidrBlocks.size() > 0) {
        List<Subnet> subnets2 = awsDescribeService.getSubnets(userNo, platformNo);
        for (Subnet subnet : subnets2) {
            if (cidrBlocks.contains(subnet.getCidrBlock())) {
                subnets.add(subnet);
            }
        }
    }
    return subnets;
}
 
Example #19
Source File: AwsVolumeResourceBuilder.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
private String getAvailabilityZoneFromSubnet(AuthenticatedContext auth, CloudResource subnetResource) {
    AmazonEc2RetryClient amazonEC2Client = getAmazonEC2Client(auth);
    DescribeSubnetsResult describeSubnetsResult = amazonEC2Client.describeSubnets(new DescribeSubnetsRequest()
            .withSubnetIds(subnetResource.getName()));
    return describeSubnetsResult.getSubnets().stream()
            .filter(subnet -> subnetResource.getName().equals(subnet.getSubnetId()))
            .map(Subnet::getAvailabilityZone)
            .findFirst()
            .orElse(auth.getCloudContext().getLocation().getAvailabilityZone().value());
}
 
Example #20
Source File: AwsCommonProcess.java    From primecloud-controller with GNU General Public License v2.0 5 votes vote down vote up
public List<Subnet> describeSubnetsByVpcId(AwsProcessClient awsProcessClient, String vpcId) {
    DescribeSubnetsRequest request = new DescribeSubnetsRequest();
    request.withFilters(new Filter().withName("vpc-id").withValues(vpcId));
    DescribeSubnetsResult result = awsProcessClient.getEc2Client().describeSubnets(request);
    List<Subnet> subnets = result.getSubnets();

    return subnets;
}
 
Example #21
Source File: BaseTest.java    From aws-mock with MIT License 5 votes vote down vote up
/**
 * Create Subnet.
 *
 * @param cidrBlock the cidr block
 * @param vpcId the vpc id
 * @return Subnet
 */
protected final Subnet createSubnet(final String cidrBlock, final String vpcId) {
    Subnet subnet = null;

    CreateSubnetRequest req = new CreateSubnetRequest();
    req.setCidrBlock(cidrBlock);
    req.setVpcId(vpcId);
    CreateSubnetResult result = amazonEC2Client.createSubnet(req);
    if (result != null) {
        subnet = result.getSubnet();
    }

    return subnet;
}
 
Example #22
Source File: AwsNetworkService.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
public List<String> getExistingSubnetCidr(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);
    DescribeSubnetsRequest subnetsRequest = new DescribeSubnetsRequest().withSubnetIds(awsNetworkView.getSubnetList());
    List<Subnet> subnets = ec2Client.describeSubnets(subnetsRequest).getSubnets();
    if (subnets.isEmpty()) {
        throw new CloudConnectorException("The specified subnet does not exist (maybe it's in a different region).");
    }
    List<String> cidrs = Lists.newArrayList();
    for (Subnet subnet : subnets) {
        cidrs.add(subnet.getCidrBlock());
    }
    return cidrs;
}
 
Example #23
Source File: EC2Utils.java    From wildfly-camel with Apache License 2.0 5 votes vote down vote up
public static String getSubnetId(AmazonEC2Client ec2Client) {
    Subnet subnet = null;
    for (Subnet aux : ec2Client.describeSubnets().getSubnets()) {
        System.out.println();
        if (aux.getState().equals("available") && aux.getAvailabilityZone().startsWith("eu-west-1")) {
            subnet = aux;
            break;
        }
    }
    Assert.assertNotNull("Subnet not null", subnet);
    return subnet.getSubnetId();
}
 
Example #24
Source File: Ec2NetworkTest.java    From aws-mock with MIT License 5 votes vote down vote up
/**
 * Test describing Subnets.
 */
@Test(timeout = TIMEOUT_LEVEL1)
public final void describeSubnetTest() {
    log.info("Start describing Subnet test");
    createSubnetTest();
    Subnet subnet = getSubnet();

    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 #25
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 #26
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 #27
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 #28
Source File: BaseTest.java    From aws-mock with MIT License 5 votes vote down vote up
/**
 * Describe Subnet.
 *
 * @return Subnet
 */
protected final Subnet getSubnet() {
    Subnet subnet = null;

    DescribeSubnetsRequest req = new DescribeSubnetsRequest();
    DescribeSubnetsResult result = amazonEC2Client.describeSubnets(req);
    if (result != null && !result.getSubnets().isEmpty()) {
        subnet = result.getSubnets().get(0);
    }

    return subnet;
}
 
Example #29
Source File: BaseTest.java    From aws-mock with MIT License 5 votes vote down vote up
/**
 * Describe Subnets.
 * @return List of Subnet
 */
protected final List<Subnet> getSubnets() {
    List<Subnet> subnets = null;

    DescribeSubnetsRequest req = new DescribeSubnetsRequest();
    DescribeSubnetsResult result = amazonEC2Client.describeSubnets(req);
    if (result != null && !result.getSubnets().isEmpty()) {
        subnets = result.getSubnets();
    }

     return subnets;
  }
 
Example #30
Source File: EmrPricingHelper.java    From herd with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a list of subnets specified in the definition. The definition specifies a comma-separated list of subnet IDs. This method parses it, looks up the
 * subnet from AWS, and returns the list. If the subnet is not specified or empty, all subnets in the current VPC is returned. This is AWS's default
 * behavior. All subnet IDs will be trimmed, and ignored if empty.
 *
 * @param emrClusterDefinition the definition specifying the subnet IDs
 * @param awsParamsDto the AWS related parameters for access/secret keys and proxy details
 *
 * @return the list of subnets
 */
private List<Subnet> getSubnets(EmrClusterDefinition emrClusterDefinition, AwsParamsDto awsParamsDto)
{
    String definitionSubnetId = emrClusterDefinition.getSubnetId();

    Set<String> subnetIds = Collections.emptySet();
    if (StringUtils.isNotBlank(definitionSubnetId))
    {
        subnetIds = herdStringHelper.splitAndTrim(definitionSubnetId, ",");
    }

    return ec2Dao.getSubnets(subnetIds, awsParamsDto);
}