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

The following examples show how to use com.amazonaws.services.ec2.model.Filter. 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: AwsDescribeServiceImpl.java    From primecloud-controller with GNU General Public License v2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public List<SecurityGroup> getSecurityGroups(Long userNo, Long platformNo) {
    // セキュリティグループを取得
    AwsProcessClient awsProcessClient = awsProcessClientFactory.createAwsProcessClient(userNo, platformNo);
    DescribeSecurityGroupsRequest request = new DescribeSecurityGroupsRequest();
    PlatformAws platformAws = platformAwsDao.read(platformNo);
    if (BooleanUtils.isTrue(platformAws.getVpc())) {
        // VPCの場合、VPC IDが同じものを抽出
        request.withFilters(new Filter().withName("vpc-id").withValues(platformAws.getVpcId()));
    } else {
        // 非VPCの場合、VPC IDが空のものを抽出
        request.withFilters(new Filter().withName("vpc-id").withValues(""));
    }
    DescribeSecurityGroupsResult result = awsProcessClient.getEc2Client().describeSecurityGroups(request);
    List<SecurityGroup> securityGroups = result.getSecurityGroups();

    // ソート
    Collections.sort(securityGroups, Comparators.COMPARATOR_SECURITY_GROUP);

    return securityGroups;
}
 
Example #2
Source File: AwsEc2SeedHostsProvider.java    From crate with Apache License 2.0 6 votes vote down vote up
private DescribeInstancesRequest buildDescribeInstancesRequest() {
    final DescribeInstancesRequest describeInstancesRequest = new DescribeInstancesRequest()
        .withFilters(
            new Filter("instance-state-name").withValues("running", "pending")
        );

    for (final Map.Entry<String, List<String>> tagFilter : tags.entrySet()) {
        // for a given tag key, OR relationship for multiple different values
        describeInstancesRequest.withFilters(
            new Filter("tag:" + tagFilter.getKey()).withValues(tagFilter.getValue())
        );
    }

    if (!availabilityZones.isEmpty()) {
        // OR relationship amongst multiple values of the availability-zone filter
        describeInstancesRequest.withFilters(
            new Filter("availability-zone").withValues(availabilityZones)
        );
    }

    return describeInstancesRequest;
}
 
Example #3
Source File: EC2Utils.java    From amazon-kinesis-connectors with Apache License 2.0 6 votes vote down vote up
/**
 * Return the DNS name of one Amazon EC2 instance with the provided filter name and value.
 * 
 * @param ec2Client
 *        an Amazon EC2 instance
 * @param filterName
 *        the name of the filter
 * @param filterValue
 *        the value of the filter
 * @return the public DNS name of an instance with the filter name and value. Null if none exist.
 */
public static String getEndpointForFirstActiveInstanceWithTag(AmazonEC2 ec2Client,
        String filterName,
        String filterValue) {
    DescribeInstancesRequest describeInstancesRequest =
            new DescribeInstancesRequest().withFilters(new Filter().withName(filterName).withValues(filterValue));
    DescribeInstancesResult describeInstancesResult = ec2Client.describeInstances(describeInstancesRequest);

    List<Reservation> reservations = describeInstancesResult.getReservations();
    for (Reservation reservation : reservations) {
        List<Instance> ec2Instances = reservation.getInstances();
        for (Instance ec2Instance : ec2Instances) {
            if (InstanceStateName.Running.toString().equals(ec2Instance.getState().getName())) {
                return ec2Instance.getPublicDnsName();
            }
        }
    }
    return null;
}
 
Example #4
Source File: AwsNetworkService.java    From cloudbreak with Apache License 2.0 6 votes vote down vote up
public 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.debug("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.debug("The selected VPCs: {}, has the following subnets: {}", vpc.getVpcId(), String.join(",", subnetCidrs));

    return calculateSubnet(ac.getCloudContext().getName(), vpc, subnetCidrs);
}
 
Example #5
Source File: AutomationReaperTask.java    From SeleniumGridScaler with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void doWork() {
    log.info("Running " + AutomationReaperTask.NAME);
    DescribeInstancesRequest describeInstancesRequest = new DescribeInstancesRequest();
    Filter filter = new Filter("tag:LaunchSource");
    filter.withValues("SeleniumGridScalerPlugin");
    describeInstancesRequest.withFilters(filter);
    List<Reservation> reservations = ec2.describeInstances(describeInstancesRequest);
    for(Reservation reservation : reservations) {
        for(Instance instance : reservation.getInstances()) {
            // Look for orphaned nodes
            Date threshold = AutomationUtils.modifyDate(new Date(),-30, Calendar.MINUTE);
            String instanceId = instance.getInstanceId();
            // If we found a node old enough AND we're not internally tracking it, this means this is an orphaned node and we should terminate it
            if(threshold.after(instance.getLaunchTime()) && !AutomationContext.getContext().nodeExists(instanceId)) {
                log.info("Terminating orphaned node: " + instanceId);
                ec2.terminateInstance(instanceId);
            }
        }
    }
}
 
Example #6
Source File: AmazonEc2InstanceUserTagsFactoryBean.java    From spring-cloud-aws with Apache License 2.0 6 votes vote down vote up
@Override
protected Map<String, String> createInstance() throws Exception {
	LinkedHashMap<String, String> properties = new LinkedHashMap<>();
	DescribeTagsResult tags = this.amazonEc2
			.describeTags(
					new DescribeTagsRequest()
							.withFilters(
									new Filter("resource-id",
											Collections.singletonList(this.idProvider
													.getCurrentInstanceId())),
									new Filter("resource-type",
											Collections.singletonList("instance"))));
	for (TagDescription tag : tags.getTags()) {
		properties.put(tag.getKey(), tag.getValue());
	}
	return properties;
}
 
Example #7
Source File: AWSSdkClient.java    From incubator-gobblin with Apache License 2.0 6 votes vote down vote up
/***
 * Get list of EC2 {@link Instance}s for a auto scaling group
 *
 * @param groupName Auto scaling group name
 * @param status Instance status (eg. running)
 * @return List of EC2 instances found for the input auto scaling group
 */
public List<Instance> getInstancesForGroup(String groupName,
    String status) {

  final AmazonEC2 amazonEC2 = getEc2Client();

  final DescribeInstancesResult instancesResult = amazonEC2.describeInstances(new DescribeInstancesRequest()
      .withFilters(new Filter().withName("tag:aws:autoscaling:groupName").withValues(groupName)));

  final List<Instance> instances = new ArrayList<>();
  for (Reservation reservation : instancesResult.getReservations()) {
    for (Instance instance : reservation.getInstances()) {
      if (null == status|| null == instance.getState()
          || status.equals(instance.getState().getName())) {
        instances.add(instance);
        LOGGER.info("Found instance: " + instance + " which qualified filter: " + status);
      } else {
        LOGGER.info("Found instance: " + instance + " but did not qualify for filter: " + status);
      }
    }
  }

  return instances;
}
 
Example #8
Source File: Ec2Facade.java    From aws-service-catalog-terraform-reference-architecture with Apache License 2.0 6 votes vote down vote up
public String getInstanceId(Tag instanceTag) {
    Filter tagFilter = new Filter("tag:" + instanceTag.getKey(), ImmutableList.of(instanceTag.getValue()));
    DescribeInstancesRequest request = new DescribeInstancesRequest().withFilters(tagFilter, RUNNING_INSTANCE_FILTER);
    DescribeInstancesResult result = ec2.describeInstances(request);

    List<String> instanceIds;
    if (result.getReservations() != null) {
        instanceIds = result.getReservations().stream()
                .flatMap(reservation -> reservation.getInstances().stream())
                .map(Instance::getInstanceId)
                .collect(ImmutableList.toImmutableList());
    } else {
        instanceIds = ImmutableList.of();
    }

    if (instanceIds.isEmpty()) {
        String message = String.format(
                "Invalid FulfillmentConfig. No instances found with TagKey: %s and TagValue: %s",
                instanceTag.getKey(),
                instanceTag.getValue());
        throw new RuntimeException(message);
    }

    int randomIndex = randomGenerator.nextInt(instanceIds.size());
    return instanceIds.get(randomIndex);
}
 
Example #9
Source File: AwsIaasGatewayScriptService.java    From primecloud-controller with GNU General Public License v2.0 6 votes vote down vote up
@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;
}
 
Example #10
Source File: TaupageExpirationTimeProviderImplTest.java    From fullstop with Apache License 2.0 6 votes vote down vote up
@Test
public void getExpirationTime() {
    final DescribeTagsResult response = new DescribeTagsResult()
            .withTags(new TagDescription()
                    .withResourceType("image")
                    .withResourceId(IMAGE_ID)
                    .withKey(TaupageExpirationTimeProviderImpl.TAG_KEY)
                    .withValue("2018-06-20T03:00:00+02:00"));

    when(mockEC2Client.describeTags(any(DescribeTagsRequest.class))).thenReturn(response);

    final ZonedDateTime result = expirationTimeProvider.getExpirationTime(REGION_NAME, IMAGE_OWNER, IMAGE_ID);
    assertThat(result).isEqualTo(ZonedDateTime.of(2018, 6, 20, 3, 0, 0, 0, ZoneOffset.ofHours(2)));

    verify(mockClientProvider).getClient(eq(AmazonEC2Client.class), eq(IMAGE_OWNER), eq(getRegion(fromName(REGION_NAME))));
    verify(mockEC2Client).describeTags(
            eq(new DescribeTagsRequest().withFilters(
                    new Filter("resource-id").withValues(IMAGE_ID),
                    new Filter("resource-type").withValues("image"),
                    new Filter("key").withValues(TaupageExpirationTimeProviderImpl.TAG_KEY))));
}
 
Example #11
Source File: TaupageExpirationTimeProviderImpl.java    From fullstop with Apache License 2.0 6 votes vote down vote up
@Override
@Cacheable(cacheNames = "ami-expiration-time", cacheManager = "oneMinuteTTLCacheManager")
public ZonedDateTime getExpirationTime(String regionName, String imageOwner, String imageId) {
    // tags are only visible in the owning account of the image
    final AmazonEC2Client ec2 = clientProvider.getClient(AmazonEC2Client.class, imageOwner,
            Region.getRegion(Regions.fromName(regionName)));
    final DescribeTagsRequest tagsRequest = new DescribeTagsRequest().withFilters(
            new Filter("resource-id").withValues(imageId),
            new Filter("resource-type").withValues("image"),
            new Filter("key").withValues(TAG_KEY));
    return ec2.describeTags(tagsRequest).getTags().stream()
            .findFirst()
            .map(TagDescription::getValue)
            .map(value -> ZonedDateTime.parse(value, ISO_DATE_TIME))
            .orElse(null);
}
 
Example #12
Source File: ResourceTaggingManager.java    From pacbot with Apache License 2.0 6 votes vote down vote up
/**
 *
 * @param resourceId
 * @param clientMap
 * @return
 */
private String getEC2PacManTagValue(String resourceId, Map<String, Object> clientMap) {
    AmazonEC2 ec2Client = (AmazonEC2) clientMap.get("client");
    DescribeTagsRequest describeTagsRequest = new DescribeTagsRequest();
    Filter filter = new Filter("resource-id");
    filter.setValues(Arrays.asList(resourceId));
    describeTagsRequest.setFilters(Arrays.asList(filter));
    DescribeTagsResult describeTagsResult = ec2Client.describeTags(describeTagsRequest);
    List<TagDescription> descriptions = describeTagsResult.getTags();
    TagDescription tagDescription = null;
    Optional<TagDescription> optional = descriptions.stream()
            .filter(obj -> obj.getKey().equals(PacmanSdkConstants.PACMAN_AUTO_FIX_TAG_NAME)).findAny();
    if (optional.isPresent()) {
        tagDescription = optional.get();
    } else {
        return null;
    }
    return tagDescription.getValue();
}
 
Example #13
Source File: SGLookupService.java    From Gatekeeper with Apache License 2.0 6 votes vote down vote up
private List<String> loadSgsForAccountRegion(AWSEnvironment environment) {
    logger.info("Grabbing SGs for environment " + environment);
    DescribeSecurityGroupsRequest describeSecurityGroupsRequest = new DescribeSecurityGroupsRequest();

    Filter groupNameFilter = new Filter();
    groupNameFilter.setName("group-name");
    groupNameFilter.setValues(Arrays.asList(securityGroupNames.split(",")));

    AmazonEC2Client amazonEC2Client = awsSessionService.getEC2Session(environment);
    DescribeSecurityGroupsResult result = amazonEC2Client.describeSecurityGroups(describeSecurityGroupsRequest.withFilters(groupNameFilter));

    logger.info("found " + result.getSecurityGroups().size() + " Security Groups with name(s) '" + securityGroupNames + "'");
    return result.getSecurityGroups().stream()
            .map(SecurityGroup::getGroupId)
            .collect(Collectors.toList());

}
 
Example #14
Source File: EC2CommunicationTest.java    From development with Apache License 2.0 6 votes vote down vote up
@Test
public void testResolveAMIFound() throws Exception {
    ec2mock.createDescribeImagesResult("image1");
    Image result = ec2comm.resolveAMI("image1");
    assertEquals("image1", result.getImageId());

    ArgumentCaptor<DescribeImagesRequest> argCaptor = ArgumentCaptor
            .forClass(DescribeImagesRequest.class);
    verify(ec2).describeImages(argCaptor.capture());
    DescribeImagesRequest dir = argCaptor.getValue();
    for (Filter filter : dir.getFilters()) {
        if (filter.getName().equals("name")) {
            assertEquals("image1", filter.getValues().get(0));
        }
    }
}
 
Example #15
Source File: AwsHelperTest.java    From attic-stratos with Apache License 2.0 5 votes vote down vote up
@Test
public void testSecurityGroupFilters()
  throws LoadBalancerExtensionException, NoSuchMethodException, InvocationTargetException,
         IllegalAccessException {
 Set<Filter> filters=(Set<Filter>)genericInvokMethod(new AWSHelper(null,null), "getFilters",2,"Test VPC ID","test");

 Assert.assertNotNull(filters);
 Assert.assertEquals(2,filters.size());

}
 
Example #16
Source File: PacmanEc2Utils.java    From pacbot with Apache License 2.0 5 votes vote down vote up
public static Filter setFilters(String filterName, String filterValue) {

        Filter filter = new Filter();
        filter.setName(filterName);
        filter.setValues(Arrays.asList(filterValue));
        return filter;
    }
 
Example #17
Source File: BaseTest.java    From aws-mock with MIT License 5 votes vote down vote up
/**
 * Create a filter to only get non terminated instances.
 *
 * @return list of instances
 */
protected final Filter getNonTerminatedInstancesFilter() {
    List<String> stateValues = new ArrayList<String>(
            Arrays.asList(InstanceState.RUNNING.getName(),
                    InstanceState.PENDING.getName(), InstanceState.STOPPING.getName(),
                    InstanceState.STOPPED.getName(), InstanceState.SHUTTING_DOWN.getName()));

    Filter runningInstanceFilter = new Filter();
    runningInstanceFilter.setValues(stateValues);
    return runningInstanceFilter;
}
 
Example #18
Source File: BaseTest.java    From aws-mock with MIT License 5 votes vote down vote up
/**
 * Describe non terminated instances.
 *
 * @param instanceIds
 *            instances' IDs
 * @return list of non terminated instances
 */
protected final List<Instance> describeNonTerminatedInstances(
        final List<Instance> instanceIds) {
    DescribeInstancesRequest request = new DescribeInstancesRequest();
    request.setInstanceIds(getInstanceIds(instanceIds));

    // set the request filter
    Filter nonTerminatedFilter = getNonTerminatedInstancesFilter();
    request.getFilters().add(nonTerminatedFilter);

    DescribeInstancesResult result = amazonEC2Client
            .describeInstances(request);
    Assert.assertTrue(result.getReservations().size() > 0);

    List<Instance> instanceList = new ArrayList<Instance>();

    for (Reservation reservation : result.getReservations()) {
        List<Instance> instances = reservation.getInstances();

        if (null != instances) {
            for (Instance i : instances) {
                instanceList.add(i);
            }
        }
    }

    return instanceList;
}
 
Example #19
Source File: AwsPlatformResources.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
private DescribeAvailabilityZonesRequest getDescribeAvailabilityZonesRequest(AmazonEC2Client ec2Client, com.amazonaws.services.ec2.model.Region awsRegion) {
    DescribeAvailabilityZonesRequest describeAvailabilityZonesRequest = new DescribeAvailabilityZonesRequest();
    ec2Client.setRegion(RegionUtils.getRegion(awsRegion.getRegionName()));
    Filter filter = new Filter();
    filter.setName("region-name");
    Collection<String> list = new ArrayList<>();
    list.add(awsRegion.getRegionName());
    filter.setValues(list);
    describeAvailabilityZonesRequest.withFilters(filter);
    return describeAvailabilityZonesRequest;
}
 
Example #20
Source File: AwsPlatformResources.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
@Override
public CloudSecurityGroups securityGroups(CloudCredential cloudCredential, Region region, Map<String, String> filters) {
    Map<String, Set<CloudSecurityGroup>> result = new HashMap<>();
    Set<CloudSecurityGroup> cloudSecurityGroups = new HashSet<>();
    AmazonEC2Client ec2Client = awsClient.createAccess(new AwsCredentialView(cloudCredential), region.value());

    //create securitygroup filter view
    PlatformResourceSecurityGroupFilterView filter = new PlatformResourceSecurityGroupFilterView(filters);

    DescribeSecurityGroupsRequest describeSecurityGroupsRequest = new DescribeSecurityGroupsRequest();
    // If the filtervalue is provided then we should filter only for those securitygroups
    if (!Strings.isNullOrEmpty(filter.getVpcId())) {
        describeSecurityGroupsRequest.withFilters(new Filter("vpc-id", singletonList(filter.getVpcId())));
    }
    if (!Strings.isNullOrEmpty(filter.getGroupId())) {
        describeSecurityGroupsRequest.withGroupIds(filter.getGroupId());
    }
    if (!Strings.isNullOrEmpty(filter.getGroupName())) {
        describeSecurityGroupsRequest.withGroupNames(filter.getGroupName());
    }

    for (SecurityGroup securityGroup : fetchSecurityGroups(ec2Client, describeSecurityGroupsRequest)) {
        Map<String, Object> properties = new HashMap<>();
        properties.put("vpcId", securityGroup.getVpcId());
        properties.put("description", securityGroup.getDescription());
        properties.put("ipPermissions", securityGroup.getIpPermissions());
        properties.put("ipPermissionsEgress", securityGroup.getIpPermissionsEgress());
        cloudSecurityGroups.add(new CloudSecurityGroup(securityGroup.getGroupName(), securityGroup.getGroupId(), properties));
    }
    result.put(region.value(), cloudSecurityGroups);
    return new CloudSecurityGroups(result);
}
 
Example #21
Source File: AWSProvider.java    From testgrid with Apache License 2.0 5 votes vote down vote up
private static DescribeInstancesResult getDescribeInstancesResult(String stackName, String region) {
    final AmazonEC2 amazonEC2 = getAmazonEC2(region);

    DescribeInstancesRequest request = new DescribeInstancesRequest();
    request.withFilters(
            new Filter("tag:" + STACK_NAME_TAG_KEY).withValues(stackName));

    return amazonEC2.describeInstances(request);
}
 
Example #22
Source File: AmazonEc2InstanceUserTagsFactoryBeanTest.java    From spring-cloud-aws with Apache License 2.0 5 votes vote down vote up
@Test
void getObject_userTagDataAvailable_objectContainsAllAvailableKeys()
		throws Exception {
	// Arrange
	AmazonEC2 amazonEC2 = mock(AmazonEC2.class);

	InstanceIdProvider instanceIdProvider = mock(InstanceIdProvider.class);
	when(instanceIdProvider.getCurrentInstanceId()).thenReturn("1234567890");

	DescribeTagsRequest describeTagsRequest = new DescribeTagsRequest().withFilters(
			new Filter("resource-id", Collections.singletonList("1234567890")),
			new Filter("resource-type", Collections.singletonList("instance")));

	DescribeTagsResult describeTagsResult = new DescribeTagsResult().withTags(
			new TagDescription().withKey("keyA")
					.withResourceType(ResourceType.Instance).withValue("valueA"),
			new TagDescription().withKey("keyB")
					.withResourceType(ResourceType.Instance).withValue("valueB"));

	when(amazonEC2.describeTags(describeTagsRequest)).thenReturn(describeTagsResult);

	AmazonEc2InstanceUserTagsFactoryBean amazonEc2InstanceUserTagsFactoryBean = new AmazonEc2InstanceUserTagsFactoryBean(
			amazonEC2, instanceIdProvider);

	// Act
	amazonEc2InstanceUserTagsFactoryBean.afterPropertiesSet();
	Map<String, String> resultMap = amazonEc2InstanceUserTagsFactoryBean.getObject();

	// Assert
	assertThat(resultMap.get("keyA")).isEqualTo("valueA");
	assertThat(resultMap.get("keyB")).isEqualTo("valueB");
	assertThat(resultMap.containsKey("keyC")).isFalse();
}
 
Example #23
Source File: AutoDetectingStackNameProvider.java    From spring-cloud-aws with Apache License 2.0 5 votes vote down vote up
private String autoDetectStackName(String instanceId) {

		Assert.notNull(instanceId, "No valid instance id defined");
		DescribeStackResourcesResult describeStackResourcesResult = this.amazonCloudFormationClient
				.describeStackResources(new DescribeStackResourcesRequest()
						.withPhysicalResourceId(instanceId));

		if (describeStackResourcesResult != null
				&& describeStackResourcesResult.getStackResources() != null
				&& !describeStackResourcesResult.getStackResources().isEmpty()) {
			return describeStackResourcesResult.getStackResources().get(0).getStackName();
		}

		if (this.amazonEc2Client != null) {
			DescribeTagsResult describeTagsResult = this.amazonEc2Client
					.describeTags(new DescribeTagsRequest().withFilters(
							new Filter("resource-id",
									Collections.singletonList(instanceId)),
							new Filter("resource-type",
									Collections.singletonList("instance")),
							new Filter("key", Collections
									.singletonList("aws:cloudformation:stack-name"))));

			if (describeTagsResult != null && describeTagsResult.getTags() != null
					&& !describeTagsResult.getTags().isEmpty()) {
				return describeTagsResult.getTags().get(0).getValue();
			}
		}

		return null;
	}
 
Example #24
Source File: Ec2InstanceStore.java    From soundwave with Apache License 2.0 5 votes vote down vote up
@Override
public List<Instance> getInstancesForZone(AvailabilityZone zone, AmazonEC2Client client)
    throws Exception {
  OperationStats op = new OperationStats("ec2InstanceStore", "getInstancesForZone");
  try {
    List<Instance> ret = new ArrayList<>();
    DescribeInstancesRequest request = new DescribeInstancesRequest()
        .withMaxResults(1000)
        .withFilters(new Filter("availability-zone", Arrays.asList(zone.getZoneName())))
        .withSdkClientExecutionTimeout(
            600 * 1000) //10 minutes time out for total execution including retries
        .withSdkRequestTimeout(300 * 1000); //5 minutes time out for a single request

    List<Reservation> reservations = new ArrayList<>();
    DescribeInstancesResult result = client.describeInstances(request);
    while (result != null) {
      reservations.addAll(result.getReservations());
      if (result.getNextToken() != null) {
        request.setNextToken(result.getNextToken());
        result = client.describeInstances(request);
      } else {
        result = null;
      }
    }

    for (Reservation reservation : reservations) {
      //Reservation refers to one launch command in EC2. Most time it should
      //only contains one instance
      for (Instance inst : reservation.getInstances()) {
        ret.add(inst);
      }
    }
    op.succeed();
    return ret;
  } catch (Exception ex) {
    op.failed();
    throw ex;
  }
}
 
Example #25
Source File: AwsUtils.java    From chassis with Apache License 2.0 5 votes vote down vote up
/**
 * Fetches and instance's name Tag or null if it does not have one
 * @param instanceId
 * @param amazonEC2
 * @return
 */
public static String getInstanceName(String instanceId, AmazonEC2 amazonEC2){
    DescribeTagsResult result = amazonEC2.describeTags(new DescribeTagsRequest().withFilters(
            new Filter().withName("resource-id").withValues(instanceId),
            new Filter().withName("resource-type").withValues("instance"),
            new Filter().withName("key").withValues(TAG_KEY_NAME)));
    if(result.getTags().isEmpty()){
        return null;
    }
    String name = result.getTags().get(0).getValue();
    return name == null || name.trim().equals("") ? null : name;
}
 
Example #26
Source File: Ec2InstanceStore.java    From soundwave with Apache License 2.0 5 votes vote down vote up
@Override
public Map<AvailabilityZone, List<ReservedInstances>> getReservedInstancesForZone(
    AvailabilityZone zone, AmazonEC2Client client) throws Exception {

  OperationStats op = new OperationStats("ec2InstanceStore", "getReservedInstancesForZone");

  try {
    Map<AvailabilityZone, List<ReservedInstances>> ret = new HashMap<>();
    DescribeReservedInstancesRequest request = new DescribeReservedInstancesRequest()
        .withFilters(new Filter("availability-zone", Arrays.asList(zone.getZoneName())))
        .withSdkClientExecutionTimeout(
            600 * 1000) //10 minutes time out for total execution including retries
        .withSdkRequestTimeout(300 * 1000); //5 minutes time out for a single request

    DescribeReservedInstancesResult result = client.describeReservedInstances(request);
    ret.put(zone, result.getReservedInstances());

    op.succeed();
    return ret;

  } catch (Exception e) {

    op.failed();
    logger.error(ExceptionUtils.getRootCauseMessage(e));
    throw e;
  }
}
 
Example #27
Source File: AwsCommonProcess.java    From primecloud-controller with GNU General Public License v2.0 5 votes vote down vote up
public List<Subnet> describeSubnetsByVpcId(AwsProcessClient awsProcessClient, String vpcId) {
    DescribeSubnetsRequest request = new DescribeSubnetsRequest();
    request.withFilters(new Filter().withName("vpc-id").withValues(vpcId));
    DescribeSubnetsResult result = awsProcessClient.getEc2Client().describeSubnets(request);
    List<Subnet> subnets = result.getSubnets();

    return subnets;
}
 
Example #28
Source File: AwsCommonProcess.java    From primecloud-controller with GNU General Public License v2.0 5 votes vote down vote up
public List<SecurityGroup> describeSecurityGroupsByVpcId(AwsProcessClient awsProcessClient, String vpcId) {
    DescribeSecurityGroupsRequest request = new DescribeSecurityGroupsRequest();
    request.withFilters(new Filter().withName("vpc-id").withValues(vpcId));
    DescribeSecurityGroupsResult result = awsProcessClient.getEc2Client().describeSecurityGroups(request);
    List<SecurityGroup> securityGroups = result.getSecurityGroups();

    return securityGroups;
}
 
Example #29
Source File: AwsDescribeServiceImpl.java    From primecloud-controller with GNU General Public License v2.0 5 votes vote down vote up
/**
 * {@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;
}
 
Example #30
Source File: Ec2InstanceStore.java    From soundwave with Apache License 2.0 5 votes vote down vote up
private List<InstanceStatus> getInstancesStatusByZone(AvailabilityZone zone,
                                                      AmazonEC2Client client) {

  // Create this list to capture paginated async results from aws sdk
  List<InstanceStatus> statusList = new ArrayList<>();

  // Create an initial request object
  DescribeInstanceStatusRequest statusRequest = new DescribeInstanceStatusRequest()
      .withMaxResults(1000)
      .withFilters(new Filter("availability-zone", Arrays.asList(zone.getZoneName())))
      .withSdkClientExecutionTimeout(600 * 1000)
      .withSdkRequestTimeout(300 * 1000);

  // Make the request for instanceStatus
  DescribeInstanceStatusResult result = client.describeInstanceStatus(statusRequest);

  // Until more results are available we loop through this code
  while (result != null) {

    statusList.addAll(result.getInstanceStatuses());

    if (result.getNextToken() != null) {

      statusRequest.setNextToken(result.getNextToken());
      result = client.describeInstanceStatus(statusRequest);

    } else {
      result = null;
    }
  }

  // Return all statuses as a list of InstanceStatus objects
  return statusList;
}