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

The following examples show how to use com.amazonaws.services.ec2.model.Address. 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: EC2InventoryUtil.java    From pacbot with Apache License 2.0 6 votes vote down vote up
/**
 * Fetch elastic IP addresses.
 *
 * @param temporaryCredentials the temporary credentials
 * @param skipRegions the skip regions
 * @param accountId the accountId
 * @return the map
 */
public static Map<String,List<Address>> fetchElasticIPAddresses(BasicSessionCredentials temporaryCredentials, String skipRegions,String accountId,String accountName){
	
	Map<String,List<Address>> elasticIPMap = new LinkedHashMap<>();
	AmazonEC2 ec2Client ;
	String expPrefix = InventoryConstants.ERROR_PREFIX_CODE+accountId + InventoryConstants.ERROR_PREFIX_EC2 ;

	for(Region region : RegionUtils.getRegions()) { 
		try{
			if(!skipRegions.contains(region.getName())){ 
				ec2Client = AmazonEC2ClientBuilder.standard().withCredentials(new AWSStaticCredentialsProvider(temporaryCredentials)).withRegion(region.getName()).build();
				List<Address> elasticIPList = ec2Client.describeAddresses().getAddresses();
				
				if(!elasticIPList.isEmpty() ) {
					log.debug(InventoryConstants.ACCOUNT + accountId + " Type : EC2 Elastic IP "+ region.getName()+" >> " + elasticIPList.size());
					elasticIPMap.put(accountId+delimiter+accountName+delimiter+region.getName(), elasticIPList);
				}
		   	}
		}catch(Exception e){
	   		log.warn(expPrefix+ region.getName()+InventoryConstants.ERROR_CAUSE +e.getMessage()+"\"}");
			ErrorManageUtil.uploadError(accountId,region.getName(),"elasticip",e.getMessage());
	   	}
	}
	return elasticIPMap;
}
 
Example #2
Source File: EC2InventoryUtilTest.java    From pacbot with Apache License 2.0 6 votes vote down vote up
/**
 * Fetch elastic IP addresses test.
 *
 * @throws Exception the exception
 */
@SuppressWarnings("static-access")
@Test
public void fetchElasticIPAddressesTest() 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);
    
    DescribeAddressesResult describeAddressesResult = new DescribeAddressesResult();
    List<Address> elasticIPList = new ArrayList<>();
    elasticIPList.add(new Address());
    describeAddressesResult.setAddresses(elasticIPList);
    when(ec2Client.describeAddresses()).thenReturn(describeAddressesResult);
    assertThat(ec2InventoryUtil.fetchElasticIPAddresses(new BasicSessionCredentials("awsAccessKey", "awsSecretKey", "sessionToken"), 
            "skipRegions", "account","accountName").size(), is(1));
}
 
Example #3
Source File: DescribeAddresses.java    From aws-doc-sdk-examples with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args)
{
    final AmazonEC2 ec2 = AmazonEC2ClientBuilder.defaultClient();

    DescribeAddressesResult response = ec2.describeAddresses();

    for(Address address : response.getAddresses()) {
        System.out.printf(
                "Found address with public IP %s, " +
                "domain %s, " +
                "allocation id %s " +
                "and NIC id %s",
                address.getPublicIp(),
                address.getDomain(),
                address.getAllocationId(),
                address.getNetworkInterfaceId());
    }
}
 
Example #4
Source File: AwsAddressProcess.java    From primecloud-controller with GNU General Public License v2.0 6 votes vote down vote up
public Address checkAssociatedAddress(AwsProcessClient awsProcessClient, Long instanceNo, Long addressNo) {
    AwsAddress awsAddress = awsAddressDao.read(addressNo);
    String publicIp = awsAddress.getPublicIp();
    String instanceId = awsAddress.getInstanceId();

    // アドレスが関連付けられているかどうかのチェック
    Address address = awsCommonProcess.describeAddress(awsProcessClient, publicIp);

    if (StringUtils.isEmpty(address.getInstanceId())) {
        // アドレスがどのインスタンスにも関連付けられていない場合
        throw new AutoException("EPROCESS-000120", publicIp, instanceId);

    } else if (!StringUtils.equals(instanceId, address.getInstanceId())) {
        // アドレスが他インスタンスに関連付けられている場合
        throw new AutoException("EPROCESS-000121", publicIp, instanceId, address.getInstanceId());
    }

    return address;
}
 
Example #5
Source File: AwsCommonProcess.java    From primecloud-controller with GNU General Public License v2.0 6 votes vote down vote up
public Address describeAddress(AwsProcessClient awsProcessClient, String publicIp) {
    // 単一アドレスの参照
    DescribeAddressesRequest request = new DescribeAddressesRequest();
    request.withPublicIps(publicIp);
    DescribeAddressesResult result = awsProcessClient.getEc2Client().describeAddresses(request);
    List<Address> addresses = result.getAddresses();

    // API実行結果チェック
    if (addresses.size() == 0) {
        // アドレスが存在しない場合
        throw new AutoException("EPROCESS-000117", publicIp);

    } else if (addresses.size() > 1) {
        // アドレスを複数参照できた場合
        AutoException exception = new AutoException("EPROCESS-000118", publicIp);
        exception.addDetailInfo("result=" + addresses);
        throw exception;
    }

    return addresses.get(0);
}
 
Example #6
Source File: FileManager.java    From pacbot with Apache License 2.0 5 votes vote down vote up
/**
 * Generate elastic IP files.
 *
 * @param elasticIPMap the elastic IP map
 * @throws IOException Signals that an I/O exception has occurred.
 */
public static void generateElasticIPFiles(Map<String, List<Address>> elasticIPMap) throws IOException {
	String fieldNames;
	String keys;
	fieldNames = "instanceId`publicIp`allocationId`associationId`domain`networkInterfaceId`networkInterfaceOwnerId`privateIpAddress";
	keys = "discoverydate`accountid`accountname`region`instanceid`publicip`allocationid`associationid`domain`networkinterfaceid`networkinterfaceownerid`privateipaddress";
	FileGenerator.generateJson(elasticIPMap, fieldNames, "aws-elasticip.data",keys);
}
 
Example #7
Source File: AddressConverter.java    From primecloud-controller with GNU General Public License v2.0 5 votes vote down vote up
@Override
protected Address convertObject(AddressInfo from) {
    Address to = new Address();

    to.setInstanceId(from.getInstanceId());
    to.setPublicIp(from.getPublicIp());

    return to;
}
 
Example #8
Source File: AwsAddressProcess.java    From primecloud-controller with GNU General Public License v2.0 5 votes vote down vote up
/**
 * TODO: メソッドコメント
 * 
 * @param awsProcessClient
 * @param instanceNo
 */
public void startAddress(AwsProcessClient awsProcessClient, Long instanceNo) {
    // アドレス情報の取得
    List<AwsAddress> awsAddresses = awsAddressDao.readByInstanceNo(instanceNo);

    if (awsAddresses.size() > 1) {
        // アドレス情報が複数ある場合
        AutoException exception = new AutoException("EPROCESS-000202", instanceNo);
        exception.addDetailInfo("result=" + awsAddresses);
        throw exception;
    }

    if (awsAddresses.isEmpty()) {
        // アドレス情報がない場合は終了
        return;
    }

    AwsAddress awsAddress = awsAddresses.get(0);

    // インスタンスIDがない場合、インスタンスに関連付ける
    if (StringUtils.isEmpty(awsAddress.getInstanceId())) {
        // アドレスのステータスチェック
        Address address = checkAvailableAddress(awsProcessClient, instanceNo, awsAddress.getAddressNo());

        // アドレスの関連付け
        associateAddress(awsProcessClient, instanceNo, awsAddress.getAddressNo(), address);

        // インスタンスのアドレス情報を更新
        updateInstanceAddress(awsProcessClient, instanceNo, awsAddress.getAddressNo());
    }
}
 
Example #9
Source File: AwsAddressProcess.java    From primecloud-controller with GNU General Public License v2.0 5 votes vote down vote up
public Address checkAvailableAddress(AwsProcessClient awsProcessClient, Long instanceNo, Long addressNo) {
    AwsAddress awsAddress = awsAddressDao.read(addressNo);
    String publicIp = awsAddress.getPublicIp();

    Address address = awsCommonProcess.describeAddress(awsProcessClient, publicIp);

    if (!StringUtils.isEmpty(address.getInstanceId())) {
        // アドレスが何らかのインスタンスに関連付けられている場合
        throw new AutoException("EPROCESS-000119", publicIp, address.getInstanceId());
    }

    return address;
}
 
Example #10
Source File: AwsAddressProcess.java    From primecloud-controller with GNU General Public License v2.0 5 votes vote down vote up
public void associateAddress(AwsProcessClient awsProcessClient, Long instanceNo, Long addressNo, Address address) {
    AwsAddress awsAddress = awsAddressDao.read(addressNo);
    AwsInstance awsInstance = awsInstanceDao.read(instanceNo);

    // アドレスの関連付け
    AssociateAddressRequest request = new AssociateAddressRequest();
    request.withInstanceId(awsInstance.getInstanceId());

    // VPCの場合
    if (BooleanUtils.isTrue(awsProcessClient.getPlatformAws().getVpc())) {
        // 割り当てIDを指定する
        request.withAllocationId(address.getAllocationId());
    }
    // 非VPCの場合
    else {
        request.withPublicIp(awsAddress.getPublicIp());
    }

    awsProcessClient.getEc2Client().associateAddress(request);

    // ログ出力
    if (log.isInfoEnabled()) {
        log.info(MessageUtils.getMessage("IPROCESS-100131", awsAddress.getPublicIp(), awsInstance.getInstanceId()));
    }

    // イベントログ出力
    Instance instance2 = instanceDao.read(instanceNo);
    processLogger.debug(null, instance2, "AwsElasticIpAssociate",
            new Object[] { awsInstance.getInstanceId(), awsAddress.getPublicIp() });

    // データベースの更新
    awsAddress.setInstanceId(awsInstance.getInstanceId());
    awsAddressDao.update(awsAddress);
}
 
Example #11
Source File: AwsAddressProcess.java    From primecloud-controller with GNU General Public License v2.0 5 votes vote down vote up
public void disassociateAddress(AwsProcessClient awsProcessClient, Long instanceNo, Long addressNo,
        Address address) {
    AwsAddress awsAddress = awsAddressDao.read(addressNo);

    // アドレスの切り離し
    DisassociateAddressRequest request = new DisassociateAddressRequest();

    // VPCの場合
    if (BooleanUtils.isTrue(awsProcessClient.getPlatformAws().getVpc())) {
        // 関連付けIDを指定する
        request.withAssociationId(address.getAssociationId());
    }
    // 非VPCの場合
    else {
        request.withPublicIp(awsAddress.getPublicIp());
    }

    awsProcessClient.getEc2Client().disassociateAddress(request);

    // ログ出力
    if (log.isInfoEnabled()) {
        log.info(MessageUtils.getMessage("IPROCESS-100132", awsAddress.getPublicIp(), awsAddress.getInstanceId()));
    }

    //イベントログ出力
    Instance instance = instanceDao.read(instanceNo);
    processLogger.debug(null, instance, "AwsElasticIpDisassociate",
            new Object[] { awsAddress.getInstanceId(), awsAddress.getPublicIp() });

    // データベースの更新
    awsAddress.setInstanceId(null);
    awsAddressDao.update(awsAddress);
}
 
Example #12
Source File: AwsAddressProcess.java    From primecloud-controller with GNU General Public License v2.0 4 votes vote down vote up
/**
 * TODO: メソッドコメント
 * 
 * @param awsProcessClient
 * @param addressNo
 */
public void deleteAddress(AwsProcessClient awsProcessClient, Long addressNo) {
    // AWSアドレス情報の存在チェック
    AwsAddress awsAddress = awsAddressDao.read(addressNo);
    if (awsAddress == null) {
        return;
    }

    // Elastic IPのチェック
    if (StringUtils.isEmpty(awsAddress.getPublicIp())) {
        // Elastic IPが空ならAWSアドレス情報を削除して終了
        awsAddressDao.delete(awsAddress);
        return;
    }

    // Elastic IPを解放
    try {
        ReleaseAddressRequest request = new ReleaseAddressRequest();

        // VPCの場合
        if (BooleanUtils.isTrue(awsProcessClient.getPlatformAws().getVpc())) {
            // 割り当てIDを取得する
            Address address = awsCommonProcess.describeAddress(awsProcessClient, awsAddress.getPublicIp());
            request.withAllocationId(address.getAllocationId());
        }
        // 非VPCの場合
        else {
            request.withPublicIp(awsAddress.getPublicIp());
        }

        awsProcessClient.getEc2Client().releaseAddress(request);

        // イベントログ出力
        processLogger.debug(null, null, "AwsElasticIpRelease",
                new Object[] { awsProcessClient.getPlatform().getPlatformName(), awsAddress.getPublicIp() });

    } catch (Exception ignore) {
        // Elastic IPが実際には存在しない場合などに備えて、警告ログを出力して例外を握りつぶす
        log.warn(ignore.getMessage());
    }

    // AWSアドレス情報を削除
    awsAddressDao.delete(awsAddress);
}
 
Example #13
Source File: AwsAddressProcess.java    From primecloud-controller with GNU General Public License v2.0 4 votes vote down vote up
/**
 * TODO: メソッドコメント
 * 
 * @param awsProcessClient
 * @param instanceNo
 */
public void stopAddress(AwsProcessClient awsProcessClient, Long instanceNo) {
    // アドレス情報の取得
    List<AwsAddress> awsAddresses = awsAddressDao.readByInstanceNo(instanceNo);

    if (awsAddresses.size() > 1) {
        // アドレス情報が複数ある場合
        AutoException exception = new AutoException("EPROCESS-000202", instanceNo);
        exception.addDetailInfo("result=" + awsAddresses);
        throw exception;
    }

    if (awsAddresses.isEmpty()) {
        // アドレス情報がない場合は終了
        return;
    }

    AwsAddress awsAddress = awsAddresses.get(0);

    // インスタンスIDがある場合、インスタンスから切り離す
    if (StringUtils.isNotEmpty(awsAddress.getInstanceId())) {
        try {
            // アドレスのステータスチェック
            Address address = checkAssociatedAddress(awsProcessClient, instanceNo, awsAddress.getAddressNo());

            // アドレスの切り離し
            disassociateAddress(awsProcessClient, instanceNo, awsAddress.getAddressNo(), address);

            // インスタンスのアドレス情報を更新
            updateInstanceAddress(awsProcessClient, instanceNo, awsAddress.getAddressNo());

        } catch (AutoException ignore) {
            // 情報が不整合(インスタンス異常終了時など)の場合、警告ログと後始末のみ行う
            log.warn(ignore.getMessage());

            awsAddress = awsAddressDao.read(awsAddress.getAddressNo());
            awsAddress.setInstanceId(null);
            awsAddressDao.update(awsAddress);
        }
    }
}
 
Example #14
Source File: AwsElasticIpService.java    From cloudbreak with Apache License 2.0 4 votes vote down vote up
public List<String> getFreeIps(Collection<String> eips, AmazonEC2 amazonEC2Client) {
    DescribeAddressesResult addresses = amazonEC2Client.describeAddresses(new DescribeAddressesRequest().withAllocationIds(eips));
    return addresses.getAddresses().stream().filter(address -> address.getInstanceId() == null)
            .map(Address::getAllocationId).collect(Collectors.toList());
}