/** * This method returns all unused EIPs * @return returns all unused EIPs */ public List<Address> getAllUnusedEIPs(List<Address> allEIPs) { List<Address> allUnusedEIPs = new ArrayList<>(); if ( allEIPs != null || allEIPs.size() >0 ) { for(Address address: allEIPs) { if (address.getInstanceId() == null) { allUnusedEIPs.add(address); } } } System.out.println("INFO : Number of Unused EIPs : " + allUnusedEIPs.size()); List<String> EIPs = allUnusedEIPs.stream().map( e -> e.getPublicIp()).collect(Collectors.toList()); System.out.println("INFO : Unused EIPs : " + EIPs); return allUnusedEIPs; }
/** * This method returns list of Evaluation objects. * @param allUnusedEIPs * @return List<Evaluation> returns list of Evaluation objects. */ private List<Evaluation> createEvaluations(List<Address> allUnusedEIPs) { List<Evaluation> evaluations = new ArrayList<>(); if ( allUnusedEIPs == null || allUnusedEIPs.size() > 0 ) { for(Address address: allUnusedEIPs) { String EIP = address.getPublicIp(); Evaluation evaluation = new Evaluation(); evaluation.setComplianceResourceId(EIP); evaluation.setComplianceResourceType(COMPLIANCE_RESOURCE_TYPE); evaluation.setComplianceType(ComplianceType.NON_COMPLIANT); evaluation.setOrderingTimestamp(new Date()); evaluations.add(evaluation); } } System.out.println("INFO : Number of evaluations : " + evaluations.size()); return evaluations; }
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()); } }
@Test public void itShouldStartAnEC2InstanceFromAnAMI() throws ServiceBrokerException { when( ec2Client.runInstances(awsRqst(r -> r.getImageId().equals( "test_image")))).thenReturn(runInstanceResult); when(ec2Client.describeAddresses()).thenReturn( new DescribeAddressesResult().withAddresses(Collections .singleton(new Address().withPublicIp("10.10.10.10")))); when(ec2Client.describeInstanceStatus(any())).thenReturn( new DescribeInstanceStatusResult() .withInstanceStatuses(Collections .singleton(new InstanceStatus() .withInstanceState(new InstanceState() .withName("running"))))); when(hostUtils.waitForBoot(anyString(), anyInt())).thenReturn(true); assertThat(aws.startEC2Instance("test_image"), is(equalTo("test_instance"))); }
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; }
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); }
private void releaseReservedIp(AmazonEC2Client client, List<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())); } }
@Test public void testGetAllUnusedEIPs() { EC2UtilsImpl ec2UtilsImpl = new EC2UtilsImpl(); List<Address> allUnusedEIPs = ec2UtilsImpl.getAllUnusedEIPs(allEIPs); assertEquals(2, allUnusedEIPs.size()); }
@Test public void itShouldReturnAFreeElasticIp() throws ServiceBrokerException { when(ec2Client.describeAddresses()).thenReturn( new DescribeAddressesResult().withAddresses(Collections .singleton(new Address().withPublicIp("10.10.10.10")))); assertThat("10.10.10.10", is(aws.getAvaliableElasticIp())); }
@Test public void itShouldReturnOnlyOneFreeElasticIp() throws ServiceBrokerException { when(ec2Client.describeAddresses()).thenReturn( new DescribeAddressesResult().withAddresses(Arrays.asList( new Address().withPublicIp("10.10.10.10") .withInstanceId(null), new Address().withPublicIp("10.10.10.11") .withInstanceId(null)))); assertThat("10.10.10.10", is(aws.getAvaliableElasticIp())); }
@Test public void itShouldFilterOutAttachedElasticIPs() throws ServiceBrokerException { when(ec2Client.describeAddresses()).thenReturn( new DescribeAddressesResult().withAddresses(Arrays.asList( new Address().withPublicIp("10.10.10.10") .withInstanceId("the-instance"), new Address().withPublicIp("10.10.10.11") .withInstanceId(null)))); assertThat("10.10.10.11", is(aws.getAvaliableElasticIp())); }
public static Address checkExistsAddress(AmazonEC2 ec2, String targetIp) { DescribeAddressesRequest addressRequest = new DescribeAddressesRequest().withPublicIps(targetIp); DescribeAddressesResult addressResult = ec2.describeAddresses(addressRequest); List<Address> addresses = addressResult.getAddresses(); for (Address address : addresses) { String publicIp = address.getPublicIp(); if (targetIp.equals(publicIp)) { return address; } break; } return null; }
public static Address allocateAddress(AmazonEC2 ec2, DomainType domainType) { AllocateAddressRequest addressRequest = new AllocateAddressRequest().withDomain(domainType); AllocateAddressResult addressResult = ec2.allocateAddress(addressRequest); Address address = new Address().withAllocationId(addressResult.getAllocationId()) .withDomain(addressResult.getDomain()).withPublicIp(addressResult.getPublicIp()); return address; }
public static String associateAddress(AmazonEC2 ec2, Address address, String instanceId) { AssociateAddressRequest addressRequest = new AssociateAddressRequest() .withAllocationId(address.getAllocationId()).withInstanceId(instanceId); AssociateAddressResult addressResult = ec2.associateAddress(addressRequest); String associationId = addressResult.getAssociationId(); return associationId; }
/** * Stop Ec2 Instance. Realease EIP for Ec2 Instance. Disassociate EIP. */ public int execute(Ec2CommandOptions options) throws FileNotFoundException { System.out.println(getClass().getName()); String name = options.getName(); InputStream inputStream = new FileInputStream(new File(options.getCredentialsPath())); ConfigProvider.loadConfigure(inputStream); AmazonEC2 ec2 = AwsEc2Client.getEc2(); // Check Exists Instance Instance instance = AwsEc2Client.findInstanceByName(ec2, name); if (instance == null) { System.err.println("Not exists instance (name = " + name + ")."); return 2; } String instanceId = instance.getInstanceId(); String publicIp = instance.getPublicIpAddress(); System.out.println("Exists instance (id = " + instanceId + ")"); // Stop Ec2 Instance InstanceStateChange stateChange = AwsEc2Client.stopInstance(ec2, instanceId); AwsEc2Client.showStateChange(stateChange, "Stopping Instance"); // Disassociate and Release Address if (publicIp != null) { Address address = AwsEc2Client.checkExistsAddress(ec2, publicIp); if (address != null) { AwsEc2Client.disassociateAddress(ec2, address); System.out.println("Disassociated Address (" + publicIp + ")"); AwsEc2Client.releaseAddress(ec2, address); System.out.println("Released Address (" + publicIp + ")"); } } else { System.out.println("No EIP."); } return 0; }
public void releaseEIP(List<String> instanceIds) { logger.info("release EIP for instances, instanceIds={}", instanceIds); DescribeAddressesResult result = ec2.describeAddresses(new DescribeAddressesRequest().withFilters(new Filter("instance-id").withValues(instanceIds))); for (Address address : result.getAddresses()) { logger.info("release EIP, ip={}, instanceId={}", address.getPublicIp(), address.getInstanceId()); ec2.disassociateAddress(new DisassociateAddressRequest().withAssociationId(address.getAssociationId())); ec2.releaseAddress(new ReleaseAddressRequest().withAllocationId(address.getAllocationId())); } }
public NatGateway createNATGateway(String subnetId, String ip) { logger.info("create nat gateway, subnetId={}, ip={}", subnetId, ip); List<Address> addresses = AWS.vpc.ec2.describeAddresses(new DescribeAddressesRequest().withPublicIps(ip)).getAddresses(); if (addresses.isEmpty()) throw new Error("cannot find eip, ip=" + ip); Address address = addresses.get(0); if (address.getAssociationId() != null) throw new Error("eip must not associated with other resource, ip=" + ip); CreateNatGatewayRequest request = new CreateNatGatewayRequest() .withSubnetId(subnetId) .withAllocationId(address.getAllocationId()); String gatewayId = ec2.createNatGateway(request).getNatGateway().getNatGatewayId(); NatGateway gateway; while (true) { Threads.sleepRoughly(Duration.ofSeconds(30)); gateway = describeNATGateway(gatewayId); String state = gateway.getState(); if ("pending".equals(state)) continue; if ("available".equals(state)) { break; } else { throw new Error("failed to create nat gateway, gatewayId=" + gatewayId + ", state=" + state); } } return gateway; }
@Override protected Address convertObject(AddressInfo from) { Address to = new Address(); to.setInstanceId(from.getInstanceId()); to.setPublicIp(from.getPublicIp()); return to; }
/** * 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()); } }
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; }
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); }
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); }
public List<AbstractResource<?>> toEc2ElasticIPs(List<Address> addresses, String accountId, Region region, DateTime dt) { List<AbstractResource<?>> resources = new ArrayList<>(); for (Address address : addresses) { Ec2ElasticIP ec2ElasticIP = new Ec2ElasticIP(); conf(ec2ElasticIP, accountId, region, dt); ec2ElasticIP.setResource(address); resources.add(ec2ElasticIP); } log.debug("{} elastic ips found via api and converted to Ec2ElasticIP", resources.size()); return resources; }
@Override @SuppressWarnings("rawtypes") protected boolean isEqual(AbstractResource newResource) { Address oldAddress = this.getResource(); Address newAddress = (Address) newResource.getResource(); return oldAddress.equals(newAddress); }
@Override protected void update(List<Event> result, Ec2ElasticIP oldResource, Ec2ElasticIP newResource) { Address oldAddress = oldResource.getResource(); Address newAddress = newResource.getResource(); if (oldAddress.getDomain().equals("vpc")) { if (notEqual(oldAddress.getInstanceId(), newAddress.getInstanceId())) { if (StringUtils.isEmpty(oldAddress.getInstanceId()) && StringUtils.isNotEmpty(newAddress.getInstanceId())) { result.add(createEvent(oldResource, newResource, EventType.Ec2_Elastic_Ip_Associated, newAddress.getInstanceId(), newAddress.getNetworkInterfaceId(), newAddress.getPrivateIpAddress())); } else if (StringUtils.isNotEmpty(oldAddress.getInstanceId()) && StringUtils.isEmpty(newAddress.getInstanceId())) { result.add(createEvent(oldResource, newResource, EventType.Ec2_Elastic_Ip_Disassociated, oldAddress.getInstanceId(), oldAddress.getNetworkInterfaceId(), oldAddress.getPrivateIpAddress())); } else { result.add(createEvent(oldResource, newResource, EventType.Ec2_Elastic_Ip_Disassociated, oldAddress.getInstanceId(), oldAddress.getNetworkInterfaceId(), oldAddress.getPrivateIpAddress())); result.add(createEvent(oldResource, newResource, EventType.Ec2_Elastic_Ip_Associated, newAddress.getInstanceId(), newAddress.getNetworkInterfaceId(), newAddress.getPrivateIpAddress())); } } else { if (notEqual(oldAddress.getPrivateIpAddress(), newAddress.getPrivateIpAddress())) { result.add(createEvent(oldResource, newResource, EventType.Ec2_Elastic_Ip_Disassociated, oldAddress.getInstanceId(), oldAddress.getNetworkInterfaceId(), oldAddress.getPrivateIpAddress())); result.add(createEvent(oldResource, newResource, EventType.Ec2_Elastic_Ip_Associated, newAddress.getInstanceId(), newAddress.getNetworkInterfaceId(), newAddress.getPrivateIpAddress())); } } } else if (oldAddress.getDomain().equals("standard")) { if (notEqual(oldAddress.getInstanceId(), newAddress.getInstanceId())) { if (StringUtils.isEmpty(oldAddress.getInstanceId()) && StringUtils.isNotEmpty(newAddress.getInstanceId())) { result.add(createEvent(oldResource, newResource, EventType.Ec2_Elastic_Ip_Associated, newAddress.getInstanceId())); } else if (StringUtils.isNotEmpty(oldAddress.getInstanceId()) && StringUtils.isEmpty(newAddress.getInstanceId())) { result.add(createEvent(oldResource, newResource, EventType.Ec2_Elastic_Ip_Disassociated, oldAddress.getInstanceId())); } else { result.add(createEvent(oldResource, newResource, EventType.Ec2_Elastic_Ip_Disassociated, oldAddress.getInstanceId())); result.add(createEvent(oldResource, newResource, EventType.Ec2_Elastic_Ip_Associated, newAddress.getInstanceId())); } } } else { log.error("unknown domain:{}", oldAddress.getDomain()); result.add(createEvent(oldResource, newResource, EventType.Unknown)); } }
private void visitEIP(VPCDiagramBuilder vpcDiagram, Address eip) throws CfnAssistException { logger.debug("visit eip " + eip.getAllocationId()); vpcDiagram.addEIP(eip); String instanceId = eip.getInstanceId(); if (instanceId!=null) { vpcDiagram.linkEIPToInstance(eip.getPublicIp(), instanceId); } }
/** * This method returns all EIPs. * @return return all EIPs * @throws AmazonClientException */ public List<Address> getAllEIPs() throws AmazonClientException { List<Address> allEIPs = new ArrayList<>(); try { allEIPs = this.amazonEc2.describeAddresses().getAddresses(); } catch(AmazonClientException e) { System.out.println("ERROR : fetching EIPs"); e.printStackTrace(); throw e; } List<String> EIPs = allEIPs.stream().map( e -> e.getPublicIp()).collect(Collectors.toList()); System.out.println("INFO : All EIPs : " + EIPs); return allEIPs; }
public void doHandle(ConfigEvent event,Context context, AmazonConfig awsConfig, EC2UtilsImpl ec2UtilsImpl) throws IOException { // Fetch invoking event. JsonNode invokingEvent = new ObjectMapper().readTree(event.getInvokingEvent()); // Check if invoking event is of type ScheduleNotification or not. checkForInCompatibleTypes(invokingEvent); // Fetch all EIPs List<Address> allEIPs = ec2UtilsImpl.getAllEIPs(); // Fetch all Unused EIPs List<Address> allUnusedEIPs = ec2UtilsImpl.getAllUnusedEIPs(allEIPs); List<Evaluation> evaluations = createEvaluations(allUnusedEIPs); doPutEvaluations(awsConfig,event,evaluations); }
@Before public void setup() { ec2UtilsImpl = mock(EC2UtilsImpl.class); // Security Groups. sgs = new ArrayList<SecurityGroup>(); //Defining Security Group 1. This security group is COMPLIANT. SecurityGroup sg1 = new SecurityGroup(); IpPermission ip1 = new IpPermission(); ip1.setFromPort(80); ip1.setToPort(80); List<String> ipRanges = Arrays.asList("0.0.0.0/0", "148.181.0.3"); ip1.setIpRanges(ipRanges); IpPermission ip2 = new IpPermission(); ip2.setFromPort(443); ip2.setToPort(443); List<String> ip2Ranges = Arrays.asList("0.0.0.0/0", "148.181.0.3"); ip1.setIpRanges(ip2Ranges); sg1.setIpPermissions(Arrays.asList(ip1,ip2)); sg1.setGroupName("VAS_COMPLIANT"); //Defining Security Group 1. This security group is NON-COMPLIANT. SecurityGroup sg2 = new SecurityGroup(); IpPermission ip3 = new IpPermission(); ip3.setFromPort(22); ip3.setToPort(22); List<String> ipRanges3 = Arrays.asList("0.0.0.0/0"); ip3.setIpRanges(ipRanges3); sg2.setIpPermissions(Arrays.asList(ip3)); sg2.setGroupName("VAS_NONCOMPLIANT"); // Add sg1,sg2 to security groups list. sgs.addAll(Arrays.asList(sg1,sg2)); // Volumes volume1 = new Volume(); volume1.setEncrypted(Boolean.TRUE); volume1.setVolumeId("volume1"); volume2 = new Volume(); volume2.setEncrypted(Boolean.FALSE); volume2.setVolumeId("volume2"); volume3 = new Volume(); volume3.setEncrypted(Boolean.TRUE); volume3.setVolumeId("volume3"); allEBSVolumes.add(volume1); allEBSVolumes.add(volume2); allEBSVolumes.add(volume3); // Instances Instance instance1 = new Instance(); Instance instance2 = new Instance(); allInstances.addAll(Arrays.asList(instance1,instance2)); allEBSRootVolumes = Arrays.asList(allEBSVolumes.get(0)); // EIPs Address address1 = new Address(); Address address2 = new Address(); allEIPs.addAll(Arrays.asList(address1,address2)); }
private AssociateContainer(String instanceId, Address address) { super(); this.instanceId = instanceId; this.address = address; }
public static void releaseAddress(AmazonEC2 ec2, Address address) { String allocationId = address.getAllocationId(); ReleaseAddressRequest releaseAddressRequest = new ReleaseAddressRequest(); releaseAddressRequest.setAllocationId(allocationId); ec2.releaseAddress(releaseAddressRequest); }
public static void disassociateAddress(AmazonEC2 ec2, Address address) { String associationId = address.getAssociationId(); DisassociateAddressRequest disassociateAddressRequest = new DisassociateAddressRequest(); disassociateAddressRequest.setAssociationId(associationId); ec2.disassociateAddress(disassociateAddressRequest); }
private int startByName(Ec2CommandOptions options) throws FileNotFoundException { String name = options.getName(); InputStream inputStream = new FileInputStream(new File(options.getCredentialsPath())); ConfigProvider.loadConfigure(inputStream); AmazonEC2 ec2 = AwsEc2Client.getEc2(); // Check Exists Instance Instance instance = AwsEc2Client.findInstanceByName(ec2, name); if (instance == null) { System.err.println("Not exists instance (name = " + name + ")."); return 2; } String instanceId = instance.getInstanceId(); System.out.println("Exists instance (id = " + instanceId + ")"); // Start Ec2 Instance InstanceStateChange stateChange = AwsEc2Client.startInstance(ec2, instanceId); AwsEc2Client.showStateChange(stateChange, "Starting Instance"); // Allocate Address DomainType domainType = (instance.getVpcId() == null) ? DomainType.Standard : DomainType.Vpc; Address address = AwsEc2Client.allocateAddress(ec2, domainType); String publicIp = address.getPublicIp(); System.out.println("Allocated Address(" + publicIp + ", " + address.getAllocationId() + ")"); if (address != null) { // TODO: Wait for Starting Instance. waitForStartingInstance(); try { // Associate Address String associateAddress = AwsEc2Client.associateAddress(ec2, address, instanceId); System.out.println("Associated Address(" + publicIp + ", " + associateAddress + ")"); String domain = options.getDomain(); if (domain != null) { // Attach Domain to EIP AmazonRoute53 route53 = AwsRoute53Client.getRoute53(); ChangeInfo attachedResult = AwsRoute53Client.attachDomainToEip(route53, publicIp, domain); if (attachedResult != null) { System.out.println("Attached domain(" + domain + ")"); } else { System.err.println("Not Found Available Hosted Zone for specified Domain(" + domain + ")"); } } } catch (AmazonServiceException e) { AwsEc2Client.releaseAddress(ec2, address); System.out.println("Released Address (" + publicIp + ")"); return 2; } } return 0; }
/** * 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); }
/** * 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); } } }
private List<String> getFreeIps(List<String> eips, AmazonEC2Client amazonEC2Client) { DescribeAddressesResult addresses = amazonEC2Client.describeAddresses(new DescribeAddressesRequest().withAllocationIds(eips)); return addresses.getAddresses().stream().filter(address -> address.getInstanceId() == null) .map(Address::getAllocationId).collect(Collectors.toList()); }
public List<Address> getEIPFor(String vpcId) throws CfnAssistException { return cloudRepository.getEIPForVPCId(vpcId); }
public void addEIP(Address eip) throws CfnAssistException { String label = AmazonVPCFacade.createLabelFromNameAndID(eip.getAllocationId() ,eip.getPublicIp()); networkDiagram.addPublicIPAddress(eip.getPublicIp(), label); }
@Test public void shouldWalkVPCAndAddItemsForDiagram() throws CfnAssistException { Vpc vpc = vpcBuilder.setFacadeVisitExpections(awsFacade); String instanceSubnetId = vpcBuilder.getSubnetId(); Subnet instanceSubnet = vpcBuilder.getSubnet(); String dbSubnetId = vpcBuilder.getDbSubnetId(); Subnet dbSubnet = vpcBuilder.getDbSubnet(); Address eip = vpcBuilder.getEip(); LoadBalancerDescription elb = vpcBuilder.getElb(); DBInstance dbInstance = vpcBuilder.getDbInstance(); Instance instance = vpcBuilder.getInstance(); String instanceId = instance.getInstanceId(); RouteTable routeTable = vpcBuilder.getRouteTable(); NetworkAcl acl = vpcBuilder.getAcl(); NetworkAclEntry outboundEntry = vpcBuilder.getOutboundEntry(); NetworkAclEntry inboundEntry = vpcBuilder.getInboundEntry(); SecurityGroup instanceSecurityGroup = vpcBuilder.getInstanceSecurityGroup(); IpPermission instanceIpPermsInbound = vpcBuilder.getInstanceIpPermsInbound(); IpPermission instanceIpPermsOutbound = vpcBuilder.getInstanceIpPermsOutbound(); SecurityGroup dbSecurityGroup = vpcBuilder.getDBSecurityGroup(); IpPermission dbIpPermsInbound = vpcBuilder.getDbIpPermsInbound(); IpPermission dbIpPermsOutbound = vpcBuilder.getDbIpPermsOutbound(); SecurityGroup elbSecurityGroup = vpcBuilder.getElbSecurityGroup(); EasyMock.expect(diagramFactory.createVPCDiagramBuilder(vpc)).andReturn(vpcDiagramBuilder); EasyMock.expect(diagramFactory.createSubnetDiagramBuilder(vpcDiagramBuilder, instanceSubnet)).andReturn(subnetDiagramBuilder); EasyMock.expect(diagramFactory.createSubnetDiagramBuilder(vpcDiagramBuilder, dbSubnet)).andReturn(dbSubnetDiagramBuilder); subnetDiagramBuilder.add(instance); vpcDiagramBuilder.add(instanceSubnetId, subnetDiagramBuilder); vpcDiagramBuilder.add(dbSubnetId, dbSubnetDiagramBuilder); // route table & routes vpcDiagramBuilder.addAsssociatedRouteTable(routeTable, instanceSubnetId); vpcDiagramBuilder.addRoute(routeTable.getRouteTableId(), instanceSubnetId, vpcBuilder.getRouteA()); vpcDiagramBuilder.addRoute(routeTable.getRouteTableId(), instanceSubnetId, vpcBuilder.getRouteB()); vpcDiagramBuilder.addRoute(routeTable.getRouteTableId(), instanceSubnetId, vpcBuilder.getRouteC()); vpcDiagramBuilder.addAsssociatedRouteTable(routeTable, dbSubnetId); vpcDiagramBuilder.addRoute(routeTable.getRouteTableId(), dbSubnetId, vpcBuilder.getRouteA()); vpcDiagramBuilder.addRoute(routeTable.getRouteTableId(), dbSubnetId, vpcBuilder.getRouteB()); vpcDiagramBuilder.addRoute(routeTable.getRouteTableId(), dbSubnetId, vpcBuilder.getRouteC()); // eip vpcDiagramBuilder.addEIP(eip); vpcDiagramBuilder.linkEIPToInstance(eip.getPublicIp(), instanceId); // elb vpcDiagramBuilder.addELB(elb); vpcDiagramBuilder.associateELBToInstance(elb, instanceId); vpcDiagramBuilder.associateELBToSubnet(elb, instanceSubnetId); vpcDiagramBuilder.associateELBToSubnet(elb, dbSubnetId); vpcDiagramBuilder.addSecurityGroup(elbSecurityGroup); vpcDiagramBuilder.associateInstanceWithSecGroup(elb.getDNSName(), elbSecurityGroup); vpcDiagramBuilder.addSecGroupInboundPerms("secElbGroupId", vpcBuilder.getElbIpPermsInbound()); vpcDiagramBuilder.addSecGroupOutboundPerms("secElbGroupId", vpcBuilder.getElbIpPermsOutbound()); // db vpcDiagramBuilder.addDBInstance(dbInstance); vpcDiagramBuilder.associateDBWithSubnet(dbInstance, dbSubnetId); vpcDiagramBuilder.addSecurityGroup(dbSecurityGroup); vpcDiagramBuilder.associateInstanceWithSecGroup(dbInstance.getDBInstanceIdentifier(), dbSecurityGroup); vpcDiagramBuilder.addSecGroupInboundPerms("secDbGroupId",dbIpPermsInbound); vpcDiagramBuilder.addSecGroupOutboundPerms("secDbGroupId",dbIpPermsOutbound); // acl vpcDiagramBuilder.addAcl(acl); vpcDiagramBuilder.associateAclWithSubnet(acl, instanceSubnetId); vpcDiagramBuilder.addACLOutbound("aclId",outboundEntry, instanceSubnetId); vpcDiagramBuilder.addACLInbound("aclId", inboundEntry, instanceSubnetId); // sec group vpcDiagramBuilder.addSecurityGroup(instanceSecurityGroup, instanceSubnetId); vpcDiagramBuilder.associateInstanceWithSecGroup(instanceId, instanceSecurityGroup); vpcDiagramBuilder.addSecGroupInboundPerms("secGroupId",instanceIpPermsInbound, instanceSubnetId); vpcDiagramBuilder.addSecGroupOutboundPerms("secGroupId",instanceIpPermsOutbound, instanceSubnetId); diagramBuilder.add(vpcDiagramBuilder); replayAll(); VPCVisitor visitor = new VPCVisitor(diagramBuilder, awsFacade, diagramFactory); visitor.visit(vpc); verifyAll(); }
/** * Associate the specified instance with the specified public IP. * * @param instanceId * the instance to associate * @param ip * the ip to associate */ public void associateAddress(String instanceId, Address address, CountDownLatch latch);