Search in sources :

Example 1 with DescribeAddressesRequest

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

the class AWSRemoteCleanup method deleteNetworkInterfaces.

private void deleteNetworkInterfaces(String vpcId, AmazonEC2 usEastEc2Client) {
    DescribeNetworkInterfacesRequest networkInterfacesRequest = new DescribeNetworkInterfacesRequest().withFilters(new Filter(VPC_KEY, Collections.singletonList(vpcId)));
    DescribeNetworkInterfacesResult networkInterfacesResult = usEastEc2Client.describeNetworkInterfaces(networkInterfacesRequest);
    networkInterfacesResult.getNetworkInterfaces().forEach(networkInterface -> {
        DescribeAddressesRequest addressesRequest = new DescribeAddressesRequest().withFilters(new Filter(NETWORK_INTERFACE_KEY, Collections.singletonList(networkInterface.getNetworkInterfaceId())));
        DescribeAddressesResult addressResult = usEastEc2Client.describeAddresses(addressesRequest);
        addressResult.getAddresses().forEach(address -> {
            // There is no hardcore dependency on EIP, but we may run out of addresses and
            // would be good to disassociate followed by releasing them.
            DisassociateAddressRequest disassociateAddressRequest = new DisassociateAddressRequest().withAssociationId(address.getAssociationId());
            usEastEc2Client.disassociateAddress(disassociateAddressRequest);
            ReleaseAddressRequest releaseAddressRequest = new ReleaseAddressRequest().withAllocationId(address.getAllocationId());
            usEastEc2Client.releaseAddress(releaseAddressRequest);
        });
        // Deleting Network Interfaces
        DeleteNetworkInterfaceRequest deleteNetworkInterfaceRequest = new DeleteNetworkInterfaceRequest().withNetworkInterfaceId(networkInterface.getNetworkInterfaceId());
        this.host.log("Terminating stale NIC: %s", networkInterface.getNetworkInterfaceId());
        usEastEc2Client.deleteNetworkInterface(deleteNetworkInterfaceRequest);
    });
}
Also used : Filter(com.amazonaws.services.ec2.model.Filter) DisassociateAddressRequest(com.amazonaws.services.ec2.model.DisassociateAddressRequest) DescribeAddressesRequest(com.amazonaws.services.ec2.model.DescribeAddressesRequest) DescribeAddressesResult(com.amazonaws.services.ec2.model.DescribeAddressesResult) DescribeNetworkInterfacesResult(com.amazonaws.services.ec2.model.DescribeNetworkInterfacesResult) DescribeNetworkInterfacesRequest(com.amazonaws.services.ec2.model.DescribeNetworkInterfacesRequest) ReleaseAddressRequest(com.amazonaws.services.ec2.model.ReleaseAddressRequest) DeleteNetworkInterfaceRequest(com.amazonaws.services.ec2.model.DeleteNetworkInterfaceRequest)

Example 2 with DescribeAddressesRequest

use of com.amazonaws.services.ec2.model.DescribeAddressesRequest 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 3 with DescribeAddressesRequest

use of com.amazonaws.services.ec2.model.DescribeAddressesRequest in project cloudbreak by hortonworks.

the class AwsResourceConnector method releaseReservedIp.

private void releaseReservedIp(AmazonEC2 client, Iterable<CloudResource> resources) {
    CloudResource elasticIpResource = getReservedIp(resources);
    if (elasticIpResource != null && elasticIpResource.getName() != null) {
        Address address;
        try {
            DescribeAddressesResult describeResult = client.describeAddresses(new DescribeAddressesRequest().withAllocationIds(elasticIpResource.getName()));
            address = describeResult.getAddresses().get(0);
        } catch (AmazonServiceException e) {
            if (e.getErrorMessage().equals("The allocation ID '" + elasticIpResource.getName() + "' does not exist")) {
                LOGGER.warn("Elastic IP with allocation ID '{}' not found. Ignoring IP release.", elasticIpResource.getName());
                return;
            } else {
                throw e;
            }
        }
        if (address.getAssociationId() != null) {
            client.disassociateAddress(new DisassociateAddressRequest().withAssociationId(elasticIpResource.getName()));
        }
        client.releaseAddress(new ReleaseAddressRequest().withAllocationId(elasticIpResource.getName()));
    }
}
Also used : Address(com.amazonaws.services.ec2.model.Address) DisassociateAddressRequest(com.amazonaws.services.ec2.model.DisassociateAddressRequest) DescribeAddressesResult(com.amazonaws.services.ec2.model.DescribeAddressesResult) DescribeAddressesRequest(com.amazonaws.services.ec2.model.DescribeAddressesRequest) AmazonServiceException(com.amazonaws.AmazonServiceException) CloudResource(com.sequenceiq.cloudbreak.cloud.model.CloudResource) ReleaseAddressRequest(com.amazonaws.services.ec2.model.ReleaseAddressRequest)

Example 4 with DescribeAddressesRequest

use of com.amazonaws.services.ec2.model.DescribeAddressesRequest in project eureka by Netflix.

the class EIPManager method unbindEIP.

/**
 * Unbind the EIP that this instance is associated with.
 */
public void unbindEIP() throws Exception {
    InstanceInfo myInfo = applicationInfoManager.getInfo();
    String myPublicIP = null;
    if (myInfo != null && myInfo.getDataCenterInfo().getName() == Name.Amazon) {
        myPublicIP = ((AmazonInfo) myInfo.getDataCenterInfo()).get(MetaDataKey.publicIpv4);
        if (myPublicIP == null) {
            logger.info("Instance is not associated with an EIP. Will not try to unbind");
            return;
        }
        try {
            AmazonEC2 ec2Service = getEC2Service();
            DescribeAddressesRequest describeAddressRequest = new DescribeAddressesRequest().withPublicIps(myPublicIP);
            DescribeAddressesResult result = ec2Service.describeAddresses(describeAddressRequest);
            if ((result.getAddresses() != null) && (!result.getAddresses().isEmpty())) {
                Address eipAddress = result.getAddresses().get(0);
                DisassociateAddressRequest dissociateRequest = new DisassociateAddressRequest();
                String domain = eipAddress.getDomain();
                if ("vpc".equals(domain)) {
                    dissociateRequest.setAssociationId(eipAddress.getAssociationId());
                } else {
                    dissociateRequest.setPublicIp(eipAddress.getPublicIp());
                }
                ec2Service.disassociateAddress(dissociateRequest);
                logger.info("Dissociated the EIP {} from this instance", myPublicIP);
            }
        } catch (Throwable e) {
            throw new RuntimeException("Cannot dissociate address from this instance", e);
        }
    }
}
Also used : Address(com.amazonaws.services.ec2.model.Address) DisassociateAddressRequest(com.amazonaws.services.ec2.model.DisassociateAddressRequest) DescribeAddressesRequest(com.amazonaws.services.ec2.model.DescribeAddressesRequest) DescribeAddressesResult(com.amazonaws.services.ec2.model.DescribeAddressesResult) AmazonEC2(com.amazonaws.services.ec2.AmazonEC2) InstanceInfo(com.netflix.appinfo.InstanceInfo)

Example 5 with DescribeAddressesRequest

use of com.amazonaws.services.ec2.model.DescribeAddressesRequest in project eureka by Netflix.

the class EIPManager method bindEIP.

/**
 * Checks if an EIP is bound and optionally binds the EIP.
 *
 * The list of EIPs are arranged with the EIPs allocated in the zone first
 * followed by other EIPs.
 *
 * If an EIP is already bound to this instance this method simply returns. Otherwise, this method tries to find
 * an unused EIP based on information from AWS. If it cannot find any unused EIP this method, it will be retried
 * for a specified interval.
 *
 * One of the following scenarios can happen here :
 *
 *  1) If the instance is already bound to an EIP as deemed by AWS, no action is taken.
 *  2) If an EIP is already bound to another instance as deemed by AWS, that EIP is skipped.
 *  3) If an EIP is not already bound to an instance and if this instance is not bound to an EIP, then
 *     the EIP is bound to this instance.
 */
public void bindEIP() {
    InstanceInfo myInfo = applicationInfoManager.getInfo();
    String myInstanceId = ((AmazonInfo) myInfo.getDataCenterInfo()).get(MetaDataKey.instanceId);
    String myZone = ((AmazonInfo) myInfo.getDataCenterInfo()).get(MetaDataKey.availabilityZone);
    Collection<String> candidateEIPs = getCandidateEIPs(myInstanceId, myZone);
    AmazonEC2 ec2Service = getEC2Service();
    boolean isMyinstanceAssociatedWithEIP = false;
    Address selectedEIP = null;
    for (String eipEntry : candidateEIPs) {
        try {
            String associatedInstanceId;
            // Check with AWS, if this EIP is already been used by another instance
            DescribeAddressesRequest describeAddressRequest = new DescribeAddressesRequest().withPublicIps(eipEntry);
            DescribeAddressesResult result = ec2Service.describeAddresses(describeAddressRequest);
            if ((result.getAddresses() != null) && (!result.getAddresses().isEmpty())) {
                Address eipAddress = result.getAddresses().get(0);
                associatedInstanceId = eipAddress.getInstanceId();
                // already marked.
                if (((associatedInstanceId == null) || (associatedInstanceId.isEmpty()))) {
                    if (selectedEIP == null) {
                        selectedEIP = eipAddress;
                    }
                } else if (isMyinstanceAssociatedWithEIP = (associatedInstanceId.equals(myInstanceId))) {
                    // This EIP is associated with an instance, check if this is the same as the current instance.
                    // If it is the same, stop searching for an EIP as this instance is already associated with an
                    // EIP
                    selectedEIP = eipAddress;
                    break;
                } else {
                    // The EIP is used by some other instance, hence skip it
                    logger.warn("The selected EIP {} is associated with another instance {} according to AWS," + " hence skipping this", eipEntry, associatedInstanceId);
                }
            }
        } catch (Throwable t) {
            logger.error("Failed to bind elastic IP: {} to {}", eipEntry, myInstanceId, t);
        }
    }
    if (null != selectedEIP) {
        String publicIp = selectedEIP.getPublicIp();
        // Only bind if the EIP is not already associated
        if (!isMyinstanceAssociatedWithEIP) {
            AssociateAddressRequest associateAddressRequest = new AssociateAddressRequest().withInstanceId(myInstanceId);
            String domain = selectedEIP.getDomain();
            if ("vpc".equals(domain)) {
                associateAddressRequest.setAllocationId(selectedEIP.getAllocationId());
            } else {
                associateAddressRequest.setPublicIp(publicIp);
            }
            ec2Service.associateAddress(associateAddressRequest);
            logger.info("\n\n\nAssociated {} running in zone: {} to elastic IP: {}", myInstanceId, myZone, publicIp);
        }
        logger.info("My instance {} seems to be already associated with the EIP {}", myInstanceId, publicIp);
    } else {
        logger.info("No EIP is free to be associated with this instance. Candidate EIPs are: {}", candidateEIPs);
    }
}
Also used : Address(com.amazonaws.services.ec2.model.Address) DescribeAddressesRequest(com.amazonaws.services.ec2.model.DescribeAddressesRequest) DescribeAddressesResult(com.amazonaws.services.ec2.model.DescribeAddressesResult) AssociateAddressRequest(com.amazonaws.services.ec2.model.AssociateAddressRequest) AmazonEC2(com.amazonaws.services.ec2.AmazonEC2) AmazonInfo(com.netflix.appinfo.AmazonInfo) InstanceInfo(com.netflix.appinfo.InstanceInfo)

Aggregations

DescribeAddressesRequest (com.amazonaws.services.ec2.model.DescribeAddressesRequest)5 Address (com.amazonaws.services.ec2.model.Address)4 DescribeAddressesResult (com.amazonaws.services.ec2.model.DescribeAddressesResult)4 DisassociateAddressRequest (com.amazonaws.services.ec2.model.DisassociateAddressRequest)3 AmazonEC2 (com.amazonaws.services.ec2.AmazonEC2)2 ReleaseAddressRequest (com.amazonaws.services.ec2.model.ReleaseAddressRequest)2 InstanceInfo (com.netflix.appinfo.InstanceInfo)2 AmazonServiceException (com.amazonaws.AmazonServiceException)1 AmazonEC2Exception (com.amazonaws.services.ec2.model.AmazonEC2Exception)1 AssociateAddressRequest (com.amazonaws.services.ec2.model.AssociateAddressRequest)1 DeleteNetworkInterfaceRequest (com.amazonaws.services.ec2.model.DeleteNetworkInterfaceRequest)1 DescribeNatGatewaysRequest (com.amazonaws.services.ec2.model.DescribeNatGatewaysRequest)1 DescribeNetworkInterfacesRequest (com.amazonaws.services.ec2.model.DescribeNetworkInterfacesRequest)1 DescribeNetworkInterfacesResult (com.amazonaws.services.ec2.model.DescribeNetworkInterfacesResult)1 DescribeRouteTablesRequest (com.amazonaws.services.ec2.model.DescribeRouteTablesRequest)1 DescribeSubnetsRequest (com.amazonaws.services.ec2.model.DescribeSubnetsRequest)1 Filter (com.amazonaws.services.ec2.model.Filter)1 NatGateway (com.amazonaws.services.ec2.model.NatGateway)1 Route (com.amazonaws.services.ec2.model.Route)1 RouteTable (com.amazonaws.services.ec2.model.RouteTable)1