Search in sources :

Example 1 with AmazonEC2Exception

use of com.amazonaws.services.ec2.model.AmazonEC2Exception in project photon-model by vmware.

the class AWSSubnetTaskServiceTest method testCreateSubnetWithOutboundAccess.

@Test
public void testCreateSubnetWithOutboundAccess() throws Throwable {
    // provision a "public" subnet first
    SubnetState publicSubnetState = provisionSubnet(AWS_NON_EXISTING_PUBLIC_SUBNET_NAME, AWS_NON_EXISTING_PUBLIC_SUBNET_CIDR, null);
    assertNotNull(publicSubnetState.id);
    assertEquals(LifecycleState.READY, publicSubnetState.lifecycleState);
    SubnetState subnetState = provisionSubnet(AWS_NON_EXISTING_SUBNET_NAME, AWS_NON_EXISTING_SUBNET_CIDR, publicSubnetState.documentSelfLink);
    assertNotNull(subnetState.id);
    assertEquals(LifecycleState.READY, subnetState.lifecycleState);
    if (!this.isMock) {
        // Verify that the subnet was created.
        DescribeSubnetsRequest describeRequest = new DescribeSubnetsRequest().withSubnetIds(Collections.singletonList(subnetState.id));
        List<Subnet> subnets = this.client.describeSubnets(describeRequest).getSubnets();
        assertNotNull(subnets);
        assertEquals(1, subnets.size());
        // Verify that a NAT gateway was created
        assertNotNull(subnetState.customProperties);
        String natGatewayId = subnetState.customProperties.get(AWS_NAT_GATEWAY_ID);
        String routeTableId = subnetState.customProperties.get(AWS_ROUTE_TABLE_ID);
        String allocationId = subnetState.customProperties.get(AWS_ELASTIC_IP_ALLOCATION_ID);
        assertNotNull(natGatewayId);
        assertNotNull(routeTableId);
        assertNotNull(allocationId);
        DescribeNatGatewaysRequest describeNatGatewaysRequest = new DescribeNatGatewaysRequest().withNatGatewayIds(Collections.singletonList(natGatewayId));
        List<NatGateway> natGateways = this.client.describeNatGateways(describeNatGatewaysRequest).getNatGateways();
        assertNotNull(natGateways);
        assertEquals(1, natGateways.size());
        NatGateway natGateway = natGateways.get(0);
        assertEquals(publicSubnetState.id, natGateway.getSubnetId());
        assertNotNull(natGateway.getNatGatewayAddresses());
        assertEquals(1, natGateway.getNatGatewayAddresses().size());
        assertEquals(allocationId, natGateway.getNatGatewayAddresses().get(0).getAllocationId());
        assertEquals("available", natGateways.get(0).getState());
        // verify that a route table was created
        DescribeRouteTablesRequest describeRouteTablesRequest = new DescribeRouteTablesRequest().withRouteTableIds(Collections.singletonList(routeTableId));
        List<RouteTable> routeTables = this.client.describeRouteTables(describeRouteTablesRequest).getRouteTables();
        assertNotNull(routeTables);
        assertEquals(1, routeTables.size());
        RouteTable routeTable = routeTables.get(0);
        assertNotNull(routeTable.getAssociations());
        assertEquals(1, routeTable.getAssociations().size());
        assertEquals(subnetState.id, routeTable.getAssociations().get(0).getSubnetId());
        assertNotNull(routeTable.getRoutes());
        assertEquals(2, routeTable.getRoutes().size());
        boolean hasRouteToNatGateway = false;
        for (Route route : routeTable.getRoutes()) {
            if (route.getDestinationCidrBlock().equals("0.0.0.0/0") && route.getNatGatewayId() != null && route.getNatGatewayId().equals(natGatewayId)) {
                hasRouteToNatGateway = true;
                break;
            }
        }
        assertTrue(hasRouteToNatGateway);
        // Verify that an IP address allocation was created
        DescribeAddressesRequest describeAddressesRequest = new DescribeAddressesRequest().withAllocationIds(Collections.singletonList(allocationId));
        List<Address> addresses = this.client.describeAddresses(describeAddressesRequest).getAddresses();
        assertNotNull(addresses);
        assertEquals(1, addresses.size());
    }
    // delete the subnet
    kickOffSubnetProvision(InstanceRequestType.DELETE, subnetState, TaskStage.FINISHED);
    if (!this.isMock) {
        // Verify that the subnet was deleted.
        DescribeSubnetsRequest describeRequest = new DescribeSubnetsRequest().withSubnetIds(Collections.singletonList(subnetState.id));
        try {
            this.client.describeSubnets(describeRequest).getSubnets();
            fail("Subnet should not exist in AWS.");
        } catch (AmazonEC2Exception ex) {
            assertEquals(HttpResponseStatus.BAD_REQUEST.code(), ex.getStatusCode());
        }
        // Verify that the NAT gateway was deleted
        String natGatewayId = subnetState.customProperties.get(AWS_NAT_GATEWAY_ID);
        String routeTableId = subnetState.customProperties.get(AWS_ROUTE_TABLE_ID);
        String allocationId = subnetState.customProperties.get(AWS_ELASTIC_IP_ALLOCATION_ID);
        DescribeNatGatewaysRequest describeNatGatewaysRequest = new DescribeNatGatewaysRequest().withNatGatewayIds(Collections.singletonList(natGatewayId));
        List<NatGateway> natGateways = this.client.describeNatGateways(describeNatGatewaysRequest).getNatGateways();
        assertNotNull(natGateways);
        assertEquals(1, natGateways.size());
        assertEquals("deleted", natGateways.get(0).getState());
        // Verify that the route table was deleted
        DescribeRouteTablesRequest describeRouteTablesRequest = new DescribeRouteTablesRequest().withRouteTableIds(Collections.singletonList(routeTableId));
        try {
            this.client.describeRouteTables(describeRouteTablesRequest).getRouteTables();
            fail("Route table should not exist in AWS.");
        } catch (AmazonEC2Exception ex) {
            assertEquals(HttpResponseStatus.BAD_REQUEST.code(), ex.getStatusCode());
        }
        DescribeAddressesRequest describeAddressesRequest = new DescribeAddressesRequest().withAllocationIds(Collections.singletonList(allocationId));
        try {
            this.client.describeAddresses(describeAddressesRequest).getAddresses();
            fail("IP address allocation should not exist in AWS.");
        } catch (AmazonEC2Exception ex) {
            assertEquals(HttpResponseStatus.BAD_REQUEST.code(), ex.getStatusCode());
        }
    }
}
Also used : Address(com.amazonaws.services.ec2.model.Address) DescribeNatGatewaysRequest(com.amazonaws.services.ec2.model.DescribeNatGatewaysRequest) DescribeAddressesRequest(com.amazonaws.services.ec2.model.DescribeAddressesRequest) NatGateway(com.amazonaws.services.ec2.model.NatGateway) SubnetState(com.vmware.photon.controller.model.resources.SubnetService.SubnetState) RouteTable(com.amazonaws.services.ec2.model.RouteTable) DescribeRouteTablesRequest(com.amazonaws.services.ec2.model.DescribeRouteTablesRequest) Subnet(com.amazonaws.services.ec2.model.Subnet) Route(com.amazonaws.services.ec2.model.Route) AmazonEC2Exception(com.amazonaws.services.ec2.model.AmazonEC2Exception) DescribeSubnetsRequest(com.amazonaws.services.ec2.model.DescribeSubnetsRequest) BaseModelTest(com.vmware.photon.controller.model.helpers.BaseModelTest) Test(org.junit.Test)

Example 2 with AmazonEC2Exception

use of com.amazonaws.services.ec2.model.AmazonEC2Exception in project photon-model by vmware.

the class AWSNetworkService method deleteSubnetStates.

/**
 * Delete all subnet states that refer the NetworkState we are about to delete.
 */
private void deleteSubnetStates(AWSNetworkContext context, AWSNetworkStage next) {
    Query queryForReferrers = QueryUtils.queryForReferrers(context.network.documentSelfLink, SubnetState.class, SubnetState.FIELD_NAME_NETWORK_LINK);
    QueryByPages<SubnetState> subnetStates = new QueryByPages<>(getHost(), queryForReferrers, SubnetState.class, context.network.tenantLinks, context.network.endpointLink);
    subnetStates.setClusterType(ServiceTypeCluster.INVENTORY_SERVICE);
    DeferredResult<Void> query = subnetStates.queryDocuments(subnetState -> {
        // First delete Subnet in AWS
        try {
            context.client.deleteSubnet(subnetState.id);
        } catch (AmazonEC2Exception ex) {
            if (AWSNetworkClient.STATUS_CODE_SUBNET_NOT_FOUND.equals(ex.getErrorCode())) {
                // Ignore exception if the subnet is no longer available in AWS.
                this.logWarning(() -> "Unable to delete the subnet in AWS. Reason: " + ex.getMessage());
            } else {
                throw ex;
            }
        }
        // Then delete tracking SubnetState
        Operation.createDelete(this, subnetState.documentSelfLink).sendWith(this);
    });
    query.whenComplete((v, e) -> {
        if (e != null) {
            handleStages(context, e);
        } else {
            handleStages(context, next);
        }
    });
}
Also used : QueryByPages(com.vmware.photon.controller.model.query.QueryUtils.QueryByPages) Query(com.vmware.xenon.services.common.QueryTask.Query) SubnetState(com.vmware.photon.controller.model.resources.SubnetService.SubnetState) AmazonEC2Exception(com.amazonaws.services.ec2.model.AmazonEC2Exception)

Example 3 with AmazonEC2Exception

use of com.amazonaws.services.ec2.model.AmazonEC2Exception in project photon-model by vmware.

the class AWSNetworkClient method deleteSubnetAsync.

public DeferredResult<Void> deleteSubnetAsync(String subnetId) {
    DeleteSubnetRequest req = new DeleteSubnetRequest().withSubnetId(subnetId);
    String message = "Delete AWS Subnet with id [" + subnetId + "].";
    AWSDeferredResultAsyncHandler<DeleteSubnetRequest, DeleteSubnetResult> handler = new AWSDeferredResultAsyncHandler<DeleteSubnetRequest, DeleteSubnetResult>(this.service, message) {

        @Override
        protected Exception consumeError(Exception exception) {
            if (exception instanceof AmazonEC2Exception) {
                AmazonEC2Exception amazonExc = (AmazonEC2Exception) exception;
                if (STATUS_CODE_SUBNET_NOT_FOUND.equals(amazonExc.getErrorCode())) {
                    // AWS subnet doesn't exist.
                    this.service.logWarning(() -> String.format("Unable to delete AWS " + "subnet with id [%s], as it does not exist.", subnetId));
                    return RECOVERED;
                }
            }
            return exception;
        }
    };
    this.client.deleteSubnetAsync(req, handler);
    return handler.toDeferredResult().thenApply(result -> (Void) null);
}
Also used : DeleteSubnetResult(com.amazonaws.services.ec2.model.DeleteSubnetResult) DeleteSubnetRequest(com.amazonaws.services.ec2.model.DeleteSubnetRequest) AmazonEC2Exception(com.amazonaws.services.ec2.model.AmazonEC2Exception) AmazonEC2Exception(com.amazonaws.services.ec2.model.AmazonEC2Exception)

Example 4 with AmazonEC2Exception

use of com.amazonaws.services.ec2.model.AmazonEC2Exception in project photon-model by vmware.

the class AWSSecurityGroupClient method addInnerEgressRule.

public DeferredResult<Void> addInnerEgressRule(String securityGroupId) {
    AuthorizeSecurityGroupEgressRequest req = new AuthorizeSecurityGroupEgressRequest().withGroupId(securityGroupId).withIpPermissions(Collections.singletonList(buildInnerRule(securityGroupId)));
    String message = "Create internal Egress Rule on AWS Security Group with id [" + securityGroupId + "].";
    AWSDeferredResultAsyncHandler<AuthorizeSecurityGroupEgressRequest, AuthorizeSecurityGroupEgressResult> handler = new AWSDeferredResultAsyncHandler<AuthorizeSecurityGroupEgressRequest, AuthorizeSecurityGroupEgressResult>(this.service, message) {

        @Override
        protected Exception consumeError(Exception e) {
            if (e instanceof AmazonEC2Exception && ((AmazonEC2Exception) e).getErrorCode().equals(SECURITY_GROUP_RULE_DUPLICATE)) {
                Utils.log(AWSUtils.class, AWSUtils.class.getSimpleName(), Level.WARNING, () -> String.format("Egress rule already exists: %s", Utils.toString(e)));
                return null;
            } else {
                return e;
            }
        }
    };
    this.client.authorizeSecurityGroupEgressAsync(req, handler);
    return handler.toDeferredResult().thenApply(r -> (Void) null);
}
Also used : AWSUtils(com.vmware.photon.controller.model.adapters.awsadapter.AWSUtils) AuthorizeSecurityGroupEgressResult(com.amazonaws.services.ec2.model.AuthorizeSecurityGroupEgressResult) AmazonServiceException(com.amazonaws.AmazonServiceException) AmazonEC2Exception(com.amazonaws.services.ec2.model.AmazonEC2Exception) AmazonEC2Exception(com.amazonaws.services.ec2.model.AmazonEC2Exception) AuthorizeSecurityGroupEgressRequest(com.amazonaws.services.ec2.model.AuthorizeSecurityGroupEgressRequest)

Example 5 with AmazonEC2Exception

use of com.amazonaws.services.ec2.model.AmazonEC2Exception in project photon-model by vmware.

the class AWSSecurityGroupClient method addIngressRulesAsync.

public DeferredResult<Void> addIngressRulesAsync(String groupId, List<IpPermission> rules) {
    if (CollectionUtils.isNotEmpty(rules)) {
        AuthorizeSecurityGroupIngressRequest req = new AuthorizeSecurityGroupIngressRequest().withGroupId(groupId).withIpPermissions(rules);
        String message = "Create Ingress Rules on AWS Security Group with id [" + groupId + "].";
        AWSDeferredResultAsyncHandler<AuthorizeSecurityGroupIngressRequest, AuthorizeSecurityGroupIngressResult> handler = new AWSDeferredResultAsyncHandler<AuthorizeSecurityGroupIngressRequest, AuthorizeSecurityGroupIngressResult>(this.service, message) {

            @Override
            protected Exception consumeError(Exception e) {
                if (e instanceof AmazonEC2Exception && ((AmazonEC2Exception) e).getErrorCode().equals(SECURITY_GROUP_RULE_DUPLICATE)) {
                    Utils.log(AWSUtils.class, AWSUtils.class.getSimpleName(), Level.WARNING, () -> String.format("Ingress rules already exist: %s", Utils.toString(e)));
                    return null;
                } else {
                    return e;
                }
            }
        };
        this.client.authorizeSecurityGroupIngressAsync(req, handler);
        return handler.toDeferredResult().thenApply(r -> (Void) null);
    } else {
        return DeferredResult.completed(null);
    }
}
Also used : AWSUtils(com.vmware.photon.controller.model.adapters.awsadapter.AWSUtils) AuthorizeSecurityGroupIngressResult(com.amazonaws.services.ec2.model.AuthorizeSecurityGroupIngressResult) AuthorizeSecurityGroupIngressRequest(com.amazonaws.services.ec2.model.AuthorizeSecurityGroupIngressRequest) AmazonServiceException(com.amazonaws.AmazonServiceException) AmazonEC2Exception(com.amazonaws.services.ec2.model.AmazonEC2Exception) AmazonEC2Exception(com.amazonaws.services.ec2.model.AmazonEC2Exception)

Aggregations

AmazonEC2Exception (com.amazonaws.services.ec2.model.AmazonEC2Exception)15 AmazonServiceException (com.amazonaws.AmazonServiceException)7 AWSUtils (com.vmware.photon.controller.model.adapters.awsadapter.AWSUtils)6 ArrayList (java.util.ArrayList)4 AwsCredentialView (com.sequenceiq.cloudbreak.cloud.aws.view.AwsCredentialView)3 CloudInstance (com.sequenceiq.cloudbreak.cloud.model.CloudInstance)3 CloudVmInstanceStatus (com.sequenceiq.cloudbreak.cloud.model.CloudVmInstanceStatus)3 SubnetState (com.vmware.photon.controller.model.resources.SubnetService.SubnetState)3 AmazonEC2Client (com.amazonaws.services.ec2.AmazonEC2Client)2 AuthorizeSecurityGroupEgressRequest (com.amazonaws.services.ec2.model.AuthorizeSecurityGroupEgressRequest)2 AuthorizeSecurityGroupEgressResult (com.amazonaws.services.ec2.model.AuthorizeSecurityGroupEgressResult)2 AuthorizeSecurityGroupIngressRequest (com.amazonaws.services.ec2.model.AuthorizeSecurityGroupIngressRequest)2 AuthorizeSecurityGroupIngressResult (com.amazonaws.services.ec2.model.AuthorizeSecurityGroupIngressResult)2 DeleteSubnetRequest (com.amazonaws.services.ec2.model.DeleteSubnetRequest)2 DescribeInstancesResult (com.amazonaws.services.ec2.model.DescribeInstancesResult)2 DescribeSubnetsRequest (com.amazonaws.services.ec2.model.DescribeSubnetsRequest)2 DescribeVolumesResult (com.amazonaws.services.ec2.model.DescribeVolumesResult)2 Instance (com.amazonaws.services.ec2.model.Instance)2 NatGateway (com.amazonaws.services.ec2.model.NatGateway)2 Subnet (com.amazonaws.services.ec2.model.Subnet)2