/** * 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); }
/** * Create SubnetState representing AWS Subnet instance. */ private void createSubnetState(Subnet subnet, AWSNetworkContext context, AWSNetworkStage next) { SubnetState subnetState = new SubnetState(); subnetState.id = subnet.getSubnetId(); subnetState.name = subnet.getSubnetId(); subnetState.subnetCIDR = subnet.getCidrBlock(); subnetState.networkLink = context.network.documentSelfLink; subnetState.tenantLinks = context.network.tenantLinks; sendRequest( Operation.createPost(this.getHost(), SubnetService.FACTORY_LINK) .setBody(subnetState) .setCompletion((o, e) -> { if (e != null) { handleStages(context, e); return; } handleStages(context, next); })); }
/** * Async create the subnet and return it. */ public DeferredResult<Subnet> createSubnetAsync(String subnetCidr, String vpcId, String zoneId) { CreateSubnetRequest req = new CreateSubnetRequest() .withCidrBlock(subnetCidr) .withVpcId(vpcId) .withAvailabilityZone(zoneId); String message = "Create AWS Subnet with CIDR [" + subnetCidr + "] for vpc id [" + vpcId + "]."; AWSDeferredResultAsyncHandler<CreateSubnetRequest, CreateSubnetResult> handler = new AWSDeferredResultAsyncHandler<>(this.service, message); this.client.createSubnetAsync(req, handler); return handler.toDeferredResult() .thenApply(CreateSubnetResult::getSubnet); }
@Test public void testCreateSubnet() throws Throwable { SubnetState subnetState = provisionSubnet(AWS_NON_EXISTING_SUBNET_NAME, AWS_NON_EXISTING_SUBNET_CIDR, null); 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()); } }
@Test public void testDeleteSubnet() throws Throwable { Subnet awsSubnet = createAwsSubnet(); SubnetState subnetState = createSubnetState(awsSubnet.getSubnetId(), AWS_NON_EXISTING_SUBNET_NAME, AWS_NON_EXISTING_SUBNET_CIDR, null); kickOffSubnetProvision(InstanceRequestType.DELETE, subnetState, TaskStage.FINISHED); if (!this.isMock) { // Verify that the subnet was deleted. DescribeSubnetsRequest describeRequest = new DescribeSubnetsRequest() .withSubnetIds(Collections.singletonList(awsSubnet.getSubnetId())); try { this.client.describeSubnets(describeRequest).getSubnets(); fail("Subnet should not exist in AWS."); } catch (AmazonEC2Exception ex) { assertEquals(HttpResponseStatus.BAD_REQUEST.code(), ex.getStatusCode()); } } }
/** * 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())); } }
/** * 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(); }
public SubnetDTO(final Subnet subnet) { this.subnetId = subnet.getSubnetId(); this.vpcId = subnet.getVpcId(); this.state = subnet.getState(); this.availabilityZone = subnet.getAvailabilityZone(); this.cidrBlock = subnet.getCidrBlock(); this.tags.addAll( subnet.getTags() .stream() .map(TagDTO::new) .collect(Collectors.toList())); this.name = subnet.getTags() .stream() .filter(t -> t.getKey().equals("Name")) .findFirst() .map(Tag::getValue) .orElse("n/a"); }
private Map<String, Integer> planAddedCountBySubnet() { Map<String, Integer> instanceCount = Maps.newHashMap(); for (Subnet remoteSubnet : resource.subnet.remoteSubnets) { instanceCount.put(remoteSubnet.getSubnetId(), 0); } for (com.amazonaws.services.ec2.model.Instance remoteInstance : resource.remoteInstances) { instanceCount.compute(remoteInstance.getSubnetId(), (key, oldValue) -> oldValue + 1); } Map<String, Integer> addedInstanceCount = Maps.newHashMap(); for (String subnetId : instanceCount.keySet()) { addedInstanceCount.put(subnetId, 0); } for (int i = 0; i < count; i++) { String targetSubnet = findSubnetHasMinimalInstances(instanceCount); instanceCount.compute(targetSubnet, (key, oldValue) -> oldValue + 1); addedInstanceCount.compute(targetSubnet, (key, oldValue) -> oldValue + 1); } return addedInstanceCount; }
@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; }
protected 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.info("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.info("The selected VPCs: {}, has the following subnets: {}", vpc.getVpcId(), subnetCidrs.stream().collect(Collectors.joining(","))); return calculateSubnet(ac.getCloudContext().getName(), vpc, subnetCidrs); }
private void validateExistingSubnet(AwsNetworkView awsNetworkView, AmazonEC2Client 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())); } } } } }
@Test public void testUploadArtifactsToS3AndAutopopulateAsParameters() { Main main = new Main(CLIArgBuilder.createSubnetStackWithArtifactUpload(BUILD_NUMBER, testName)); int result = main.parse(); deletesStacks.ifPresent("CfnAssist9987TestsubnetWithS3Param"); assertEquals("deploy failed", 0, result); Vpc vpcId = vpcRepository.getCopyOfVpc(projectAndEnv); List<Subnet> subnets = EnvironmentSetupForTests.getSubnetFors(ec2Client, vpcId); assertEquals(1, subnets.size()); List<Tag> tags = subnets.get(0).getTags(); List<Tag> expectedTags = new LinkedList<>(); expectedTags.add(new Tag().withKey("urlATag").withValue(EnvironmentSetupForTests.S3_PREFIX+"/"+KEY_A)); expectedTags.add(new Tag().withKey("urlBTag").withValue(EnvironmentSetupForTests.S3_PREFIX+"/"+KEY_B)); assertTrue(tags.containsAll(expectedTags)); }
/** * 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()); }
@Test public void testResolveSubnet() throws Exception { ec2mock.createDescribeSubnetsResult("subnet-a77430d0"); Subnet subnet = ec2comm.resolveSubnet("subnet-a77430d0"); assertNotNull(subnet); assertEquals("subnet-a77430d0", subnet.getSubnetId()); }
public void createDescribeSubnetsResult(String... subnetIds) { Collection<Subnet> subnets = new ArrayList<Subnet>(); for (int i = 0; i < subnetIds.length; i++) { subnets.add(new Subnet().withSubnetId(subnetIds[i]) .withVpcId(subnetIds[i])); } DescribeSubnetsResult subnetResult = new DescribeSubnetsResult() .withSubnets(subnets); doReturn(subnetResult).when(ec2) .describeSubnets(any(DescribeSubnetsRequest.class)); }
public Subnet getSubnet(String subnetId) { DescribeSubnetsRequest req = new DescribeSubnetsRequest() .withSubnetIds(subnetId); DescribeSubnetsResult subnetResult = this.client.describeSubnets(req); List<Subnet> subnets = subnetResult.getSubnets(); return subnets.isEmpty() ? null : subnets.get(0); }
/** * Creates the subnet and return it. */ public Subnet createSubnet(String subnetCidr, String vpcId) { CreateSubnetRequest req = new CreateSubnetRequest() .withCidrBlock(subnetCidr) .withVpcId(vpcId); CreateSubnetResult res = this.client.createSubnet(req); return res.getSubnet(); }
/** * NOTE: Keep in mind that subnetState.networkLink is not set and it should be updated once * valid NetworkState.documentSelfLink is available. */ public static SubnetState mapSubnetToSubnetState(Subnet subnet, List<String> tenantLinks, String regionId, String parentComputeLink, String endpointLink) { if (subnet == null) { throw new IllegalArgumentException( "Cannot map Subnet to subnet state for null instance"); } SubnetState subnetState = new SubnetState(); subnetState.id = subnet.getSubnetId(); subnetState.name = subnet.getSubnetId(); subnetState.subnetCIDR = subnet.getCidrBlock(); subnetState.supportPublicIpAddress = subnet.isMapPublicIpOnLaunch(); subnetState.defaultForZone = subnet.isDefaultForAz(); subnetState.zoneId = subnet.getAvailabilityZone(); subnetState.tenantLinks = tenantLinks; subnetState.endpointLink = endpointLink; if (subnetState.endpointLinks == null) { subnetState.endpointLinks = new HashSet<>(); } subnetState.endpointLinks.add(endpointLink); subnetState.computeHostLink = parentComputeLink; subnetState.customProperties = new HashMap<>(); subnetState.regionId = regionId; if (!subnet.getTags().isEmpty()) { // The name of the subnet state is the value of the AWS_TAG_NAME tag String nameTag = getTagValue(subnet.getTags(), AWS_TAG_NAME); if (!StringUtil.isNullOrEmpty(nameTag)) { subnetState.name = nameTag; } } return subnetState; }
/** * Update the Subnet information for the VPC in question. */ @Override protected void consumeSuccess(DescribeSubnetsRequest request, DescribeSubnetsResult result) { for (Subnet subnet : result.getSubnets()) { if (!this.context.vpcs.containsKey(subnet.getVpcId())) { logWarning(() -> String.format("AWS returned Subnet [%s] with VCP [%s] that is" + " missing locally.", subnet.getSubnetId(), subnet.getVpcId())); continue; } SubnetState subnetState = mapSubnetToSubnetState(subnet, this.context.request.tenantLinks, this.context.request.regionId, this.context.request.parentComputeLink, this.context.request.request.endpointLink); if (subnetState.subnetCIDR == null) { logWarning(() -> String.format("AWS did not return CIDR information for Subnet" + " %s", subnet.toString())); } this.context.awsSubnets.put(subnet.getSubnetId(), subnet); this.context.subnets.put( subnet.getSubnetId(), new AWSNetworkStateCreationContext.SubnetStateWithParentVpcId( subnet.getVpcId(), subnetState)); } }
private Subnet createAwsSubnet() { if (this.isMock) { Subnet subnet = new Subnet(); subnet.setSubnetId(UUID.randomUUID().toString()); return subnet; } CreateSubnetRequest createRequest = new CreateSubnetRequest(AWS_DEFAULT_VPC_ID, AWS_NON_EXISTING_SUBNET_CIDR); return this.client.createSubnet(createRequest).getSubnet(); }
/** * Get the availability zone from a Subnet ID. * * @param subnetId the id of the subnet * @return the availability zone of the subnet */ private String getAvailabilityZoneFromSubnetId(String subnetId) { DescribeSubnetsRequest request = new DescribeSubnetsRequest().withSubnetIds(subnetId); DescribeSubnetsResult result = client.describeSubnets(request); Subnet subnet = Iterables.getOnlyElement(result.getSubnets()); return subnet.getAvailabilityZone(); }
/** * Chooses the best subnet from the given list of subnets, which belongs to the given availability zone. The "best" subnet is selected by the number of * available IP addresses in the subnet. A subnet with more availability is preferred. If multiple subnets have same IP availability, then the result subnet * is arbitrarily chosen. * * @param availabilityZone the availability zone in which the subnet belongs to * @param subnets the list of subnet to select from * * @return the subnet with the most number of available IPs */ private Subnet getBestSubnetForAvailabilityZone(String availabilityZone, List<Subnet> subnets) { List<Subnet> subnetsInAvailabilityZone = new ArrayList<>(); for (Subnet subnet : subnets) { if (subnet.getAvailabilityZone().equals(availabilityZone)) { subnetsInAvailabilityZone.add(subnet); } } return getTop(subnetsInAvailabilityZone, new IpAddressComparator()); }
/** * Updates the given list of subnets to remove subnets with number of available IPs less than the given value. * * @param subnets the list of subnets * @param availableIps the number of available IPs to filter by */ private void removeSubnetsWithAvailableIpsLessThan(List<Subnet> subnets, int availableIps) { Iterator<Subnet> iterator = subnets.iterator(); while (iterator.hasNext()) { Subnet subnet = iterator.next(); if (subnet.getAvailableIpAddressCount() < availableIps) { iterator.remove(); } } }
/** * 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); }
/** * This implementation uses the DescribeSubnets API. */ @Override public List<Subnet> getSubnets(Collection<String> subnetIds, AwsParamsDto awsParamsDto) { AmazonEC2Client ec2Client = getEc2Client(awsParamsDto); DescribeSubnetsRequest describeSubnetsRequest = new DescribeSubnetsRequest(); describeSubnetsRequest.setSubnetIds(subnetIds); try { DescribeSubnetsResult describeSubnetsResult = ec2Operations.describeSubnets(ec2Client, describeSubnetsRequest); return describeSubnetsResult.getSubnets(); } catch (AmazonServiceException amazonServiceException) { /* * AWS throws a 400 error when any one of the specified subnet ID is not found. * We want to catch it and throw as an handled herd error as a 404 not found. */ if (ERROR_CODE_SUBNET_ID_NOT_FOUND.equals(amazonServiceException.getErrorCode())) { throw new ObjectNotFoundException(amazonServiceException.getErrorMessage(), amazonServiceException); } // Any other type of error we throw as is because they are unexpected. else { throw amazonServiceException; } } }
/** * Converts this object into an AWS equivalent object. * * @return A new equivalent AWS object */ public Subnet toAwsObject() { Subnet subnet = new Subnet(); subnet.setSubnetId(subnetId); subnet.setAvailabilityZone(availabilityZone); subnet.setAvailableIpAddressCount(availableIpAddressCount); return subnet; }
public VpcDetailDTO(final Vpc vpc, final List<Subnet> subnets, final List<RouteTable> routeTables) { super(vpc); final Map<String, SubnetDetailDTO> subnetDetails = new HashMap<>(); subnetDetails.putAll( subnets.stream() .map(SubnetDetailDTO::new) .collect(Collectors.toMap(s -> s.getSubnetId(), identity()))); LOG.trace("Details map: {}", subnetDetails); routeTables.stream() .map(RouteTableDTO::new) .forEach(rt -> rt.getAssociations().forEach(assoc -> { SubnetDetailDTO dto = subnetDetails.get(assoc.getSubnetId()); if (dto == null) { if (LOG.isTraceEnabled()) { LOG.trace("RT: {}, Assoc.SubnetID: {}, Assocs: {}", rt.getRouteTableId(), assoc.getSubnetId(), rt.getAssociations()); } return; } dto.setRouteTableId(rt.getRouteTableId()); dto.getRoutes().addAll(rt.getRoutes()); })); this.subnets.addAll(subnetDetails.values()); }
public SubnetDetailDTO(final Subnet subnet, final RouteTable routeTable) { super(subnet); routeTableId = routeTable.getRouteTableId(); routes.addAll( routeTable.getRoutes() .stream() .map(RouteDTO::new) .collect(Collectors.toList())); }
@Override @Cacheable(value = CachingConfiguration.SUBNET_CACHE, key = "#vpcId", condition = "#bypassCache == false") public List<Subnet> getSubnetsForVpcInRegion(String vpcId, final String region, boolean bypassCache) { Preconditions.checkArgument(StringUtils.isNotBlank(vpcId), "vpcId may not be null or blank"); Preconditions.checkArgument(StringUtils.isNotBlank(region), "region may not be null or blank"); LOG.info("Retrieving subnets for VPC {} in region {} ({})", vpcId, region, bypassCache); DescribeSubnetsRequest request = new DescribeSubnetsRequest() .withFilters(new Filter() .withName("vpc-id") .withValues(vpcId)); DescribeSubnetsResult result = getClientForRegion(region).describeSubnets(request); return result.getSubnets(); }
@Override public void execute(Context context) throws Exception { ASGroupHelper helper = new ASGroupHelper(context.env); helper.createLaunchConfig(resource); CreateAutoScalingGroupRequest request = new CreateAutoScalingGroupRequest() .withAutoScalingGroupName(context.env.name + "-" + resource.id) .withLaunchConfigurationName(resource.launchConfig.remoteLaunchConfig.getLaunchConfigurationName()) .withDesiredCapacity(resource.desiredSize) .withMinSize(resource.minSize) .withMaxSize(resource.maxSize) .withDefaultCooldown(60) .withHealthCheckGracePeriod(300) // give 5 mins for server and application startup .withTerminationPolicies(ASGroup.TERMINATE_POLICY_OLDEST_INSTANCE) // always remove oldest instance, OldestLaunchConfiguration should not be used due to during deployment the old LaunchConfig can be deleted first, the ASG may fail to compare, and terminate unwanted instance .withTags(new Tag().withKey("cloud-manager:env").withValue(context.env.name).withPropagateAtLaunch(true), helper.nameTag(resource)); if (resource.elb != null) { request.withHealthCheckType("ELB") .withLoadBalancerNames(resource.elb.remoteELB.getLoadBalancerName()); } else { request.withHealthCheckType("EC2"); } List<String> availabilityZones = Lists.newArrayList(); StringBuilder subnetIds = new StringBuilder(); int index = 0; for (Subnet remoteSubnet : resource.subnet.remoteSubnets) { if (index > 0) subnetIds.append(','); subnetIds.append(remoteSubnet.getSubnetId()); availabilityZones.add(remoteSubnet.getAvailabilityZone()); index++; } request.withAvailabilityZones(availabilityZones) .withVPCZoneIdentifier(subnetIds.toString()); resource.remoteASGroup = AWS.as.createASGroup(request); }
@Override public void execute(Context context) throws Exception { CreateLoadBalancerRequest request = new CreateLoadBalancerRequest() .withLoadBalancerName(resource.name) .withScheme(resource.scheme.orElse(null)) .withTags(new Tag().withKey("cloud-manager:env").withValue(context.env.name)); if (resource.subnet != null) { request.withSecurityGroups(resource.securityGroup.remoteSecurityGroup.getGroupId()) .withSubnets(resource.subnet.remoteSubnets.stream().map(Subnet::getSubnetId).collect(Collectors.toList())); } else { List<String> zones = AWS.ec2.availabilityZones(); request.withAvailabilityZones(zones.get(0)); } if (resource.listenHTTP) { request.getListeners().add(new Listener("HTTP", 80, 80)); } if (resource.listenHTTPS) { String certARN = resource.amazonCertARN != null ? resource.amazonCertARN : resource.cert.remoteCert.getServerCertificateMetadata().getArn(); request.getListeners().add(new Listener() .withProtocol("HTTPS") .withLoadBalancerPort(443) .withInstanceProtocol("HTTP") .withInstancePort(80) .withSSLCertificateId(certARN)); } resource.remoteELB = AWS.elb.createELB(request); configureELB(context.env.region); configureHealthCheck(); context.output(String.format("elb/%s/DNS", resource.id), resource.remoteELB.getDNSName()); }
private void linkDeleteTasks() { for (DeleteSubnetTask subnetTask : all(DeleteSubnetTask.class)) { find(DeleteVPCTask.class) .ifPresent(task -> task.dependsOn(subnetTask)); for (Subnet remoteSubnet : subnetTask.resource.remoteSubnets) { linkDeleteSubnetTasks(subnetTask, remoteSubnet); } } }
private void linkDeleteSubnetTasks(DeleteSubnetTask subnetTask, Subnet remoteSubnet) { for (DeleteRouteTableTask routeTableTask : all(DeleteRouteTableTask.class)) { routeTableTask.resource.remoteRouteTable.getAssociations().stream() .filter(association -> association.getSubnetId().equals(remoteSubnet.getSubnetId())) .forEach(association -> subnetTask.dependsOn(routeTableTask)); } }
private Subnet findSubnet(String subnetId) { for (Subnet subnet : subnets) { if (StringUtils.equals(subnet.getSubnetId(), subnetId)) { return subnet; } } return null; }
public Subnet findSubnet(String subnetId) { for (Subnet subnet : subnets) { if (subnet.getSubnetId().equals(subnetId)) { return subnet; } } return null; }
/** * {@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; }