Java源码示例:com.amazonaws.services.ec2.model.DescribeImagesResult

示例1
@Override
protected void setUpRead()
{
    when(mockEc2.describeImages(any(DescribeImagesRequest.class))).thenAnswer((InvocationOnMock invocation) -> {
        DescribeImagesRequest request = (DescribeImagesRequest) invocation.getArguments()[0];

        assertEquals(getIdValue(), request.getImageIds().get(0));
        DescribeImagesResult mockResult = mock(DescribeImagesResult.class);
        List<Image> values = new ArrayList<>();
        values.add(makeImage(getIdValue()));
        values.add(makeImage(getIdValue()));
        values.add(makeImage("fake-id"));
        when(mockResult.getImages()).thenReturn(values);
        return mockResult;
    });
}
 
示例2
/**
 * Checks whether image is present.
 * 
 * @param amiID
 * @return <code>Image </code> if the matches one of the amiID
 * 
 */
public Image resolveAMI(String amiID) throws APPlatformException {
    LOGGER.debug("resolveAMI('{}') entered", amiID);
    DescribeImagesRequest dir = new DescribeImagesRequest();
    dir.withImageIds(amiID);
    DescribeImagesResult describeImagesResult = getEC2()
            .describeImages(dir);

    List<Image> images = describeImagesResult.getImages();
    for (Image image : images) {
        LOGGER.debug(image.getImageId() + "==" + image.getImageLocation()
                + "==" + image.getName());
        return image;
    }
    throw new APPlatformException(Messages.getAll("error_invalid_image")
            + amiID);
}
 
示例3
@Override
@Cacheable(cacheNames = "ami-details", cacheManager = "oneDayTTLCacheManager")
public Map<String, String> getAmiDetails(final String accountId, final Region region, final String amiId) {
    final ImmutableMap.Builder<String, String> result = ImmutableMap.builder();
    result.put("ami_id", amiId);

    final AmazonEC2Client ec2 = clientProvider.getClient(AmazonEC2Client.class, accountId, region);
    final Optional<Image> ami = Optional.ofNullable(new DescribeImagesRequest().withImageIds(amiId))
            .map(ec2::describeImages)
            .map(DescribeImagesResult::getImages)
            .map(List::stream)
            .flatMap(Stream::findFirst);

    ami.map(Image::getName).ifPresent(name -> result.put("ami_name", name));
    ami.map(Image::getOwnerId).ifPresent(owner -> result.put("ami_owner_id", owner));
    return result.build();
}
 
示例4
@Test
public void testApplyAmiFound() throws Exception {

    when(ec2InstanceContextMock.getAmiId()).thenReturn(Optional.of(AMI_ID));
    when(ec2InstanceContextMock.getClient(eq(AmazonEC2Client.class))).thenReturn(amazonEC2ClientMock);

    final DescribeImagesRequest describeImagesRequest = new DescribeImagesRequest().withImageIds(AMI_ID);
    when(amazonEC2ClientMock.describeImages(eq(describeImagesRequest)))
            .thenReturn(new DescribeImagesResult()
                    .withImages(newArrayList(new Image()
                            .withImageId(AMI_ID)
                            .withName(AMI_NAME))
                    )
            );

    final Optional<Image> result = amiProvider.apply(ec2InstanceContextMock);

    assertThat(result).isPresent();

    verify(ec2InstanceContextMock).getAmiId();
    verify(ec2InstanceContextMock).getClient(eq(AmazonEC2Client.class));
    verify(amazonEC2ClientMock).describeImages(eq(describeImagesRequest));
}
 
示例5
@Test
public void testCreateCreateStackRequestForCloudStack() {
    when(cloudContext.getLocation()).thenReturn(Location.location(Region.region("region"), new AvailabilityZone("az")));
    DescribeImagesResult imagesResult = new DescribeImagesResult();
    when(amazonEC2Client.describeImages(any(DescribeImagesRequest.class)))
            .thenReturn(imagesResult.withImages(new com.amazonaws.services.ec2.model.Image()));
    when(network.getStringParameter(anyString())).thenReturn("");

    Collection<Tag> tags = Lists.newArrayList(new Tag().withKey("mytag").withValue("myvalue"));
    when(awsTaggingService.prepareCloudformationTags(authenticatedContext, cloudStack.getTags())).thenReturn(tags);

    CreateStackRequest createStackRequest =
            underTest.createCreateStackRequest(authenticatedContext, cloudStack, "stackName", "subnet", "template");

    assertEquals("stackName", createStackRequest.getStackName());
    assertEquals("template", createStackRequest.getTemplateBody());

    verify(awsTaggingService).prepareCloudformationTags(authenticatedContext, cloudStack.getTags());
    assertEquals(tags, createStackRequest.getTags());
}
 
示例6
@Test
public void testDeleteResourcesWhenBothAMIAndSnapshotExist() {
    String encryptedImageId = "ami-87654321";
    String encryptedSnapshotId = "snap-12345678";
    Image image = new Image()
            .withImageId(encryptedImageId)
            .withBlockDeviceMappings(
                    new BlockDeviceMapping().withDeviceName("/dev/sdb").withVirtualName("ephemeral0"),
                    new BlockDeviceMapping().withEbs(new EbsBlockDevice().withEncrypted(true).withSnapshotId(encryptedSnapshotId)));
    when(ec2Client.describeImages(any()))
            .thenReturn(new DescribeImagesResult().withImages(image));

    List<CloudResource> resources = List.of(new CloudResource.Builder()
            .name(encryptedImageId)
            .type(ResourceType.AWS_ENCRYPTED_AMI)
            .build());

    underTest.deleteResources(DEFAULT_REGION, ec2Client, resources);

    verify(ec2Client, times(1)).deleteSnapshot(any());
    verify(ec2Client, times(1)).deregisterImage(any());
}
 
示例7
@Test
public void testDeleteResourcesWhenOnlyAMIExistsAndSnapshotNot() {
    String encryptedImageId = "ami-87654321";
    Image image = new Image()
            .withImageId(encryptedImageId)
            .withBlockDeviceMappings(new BlockDeviceMapping()
                    .withEbs(new EbsBlockDevice().withEncrypted(true)));
    when(ec2Client.describeImages(any()))
            .thenReturn(new DescribeImagesResult().withImages(image));
    List<CloudResource> resources = List.of(new CloudResource.Builder()
            .name(encryptedImageId)
            .type(ResourceType.AWS_ENCRYPTED_AMI)
            .build());

    underTest.deleteResources(DEFAULT_REGION, ec2Client, resources);

    verify(ec2Client, times(0)).deleteSnapshot(any());
    verify(ec2Client, times(1)).deregisterImage(any());
}
 
示例8
@Test
public void testDeleteResourcesWhenAMIDoesNotExistAtDeregisterShouldNotThrowException() {
    String encryptedImageId = "ami-87654321";
    String encryptedSnapshotId = "snap-12345678";
    String eMsg = String.format("An error occurred (%s) when calling the DeregisterImage operation: The image id '[%s]' does not exist",
            AMI_NOT_FOUND_MSG_CODE, encryptedImageId);

    Image image = new Image()
            .withImageId(encryptedImageId)
            .withBlockDeviceMappings(new BlockDeviceMapping()
                    .withEbs(new EbsBlockDevice().withEncrypted(true).withSnapshotId(encryptedSnapshotId)));
    when(ec2Client.describeImages(any()))
            .thenReturn(new DescribeImagesResult().withImages(image));
    when(ec2Client.deregisterImage(any()))
            .thenThrow(new AmazonServiceException(eMsg));
    List<CloudResource> resources = List.of(new CloudResource.Builder()
            .name(encryptedImageId)
            .type(ResourceType.AWS_ENCRYPTED_AMI)
            .build());

    underTest.deleteResources(DEFAULT_REGION, ec2Client, resources);

    verify(ec2Client, times(1)).deregisterImage(any());
    verify(ec2Client, times(0)).deleteSnapshot(any());
}
 
示例9
@Test
public void testDeleteResourcesWhenSnapshotDoesNotExistShouldNotThrowException() {
    String encryptedImageId = "ami-87654321";
    String encryptedSnapshotId = "snap-12345678";
    String eMsg = String.format("An error occurred (%s) when calling the DeleteSnapshot operation: None", SNAPSHOT_NOT_FOUND_MSG_CODE);
    Image image = new Image()
            .withImageId(encryptedImageId)
            .withBlockDeviceMappings(new BlockDeviceMapping()
                    .withEbs(new EbsBlockDevice().withEncrypted(true).withSnapshotId(encryptedSnapshotId)));
    when(ec2Client.describeImages(any()))
            .thenReturn(new DescribeImagesResult().withImages(image));
    when(ec2Client.deleteSnapshot(any()))
            .thenThrow(new AmazonServiceException(eMsg));
    List<CloudResource> resources = List.of(new CloudResource.Builder()
            .name(encryptedImageId)
            .type(ResourceType.AWS_ENCRYPTED_AMI)
            .build());

    underTest.deleteResources(DEFAULT_REGION, ec2Client, resources);

    verify(ec2Client, times(1)).deregisterImage(any());
    verify(ec2Client, times(1)).deleteSnapshot(any());
}
 
示例10
@Test
public void testDeleteResourcesWhenAMIDeregisterFailsWithEC2Client() {
    thrown.expect(CloudConnectorException.class);

    String encryptedImageId = "ami-87654321";
    String encryptedSnapshotId = "snap-12345678";
    Image image = new Image()
            .withImageId(encryptedImageId)
            .withBlockDeviceMappings(
                    new BlockDeviceMapping().withDeviceName("/dev/sdb").withVirtualName("ephemeral0"),
                    new BlockDeviceMapping().withEbs(new EbsBlockDevice().withEncrypted(true).withSnapshotId(encryptedSnapshotId)));
    when(ec2Client.describeImages(any()))
            .thenReturn(new DescribeImagesResult().withImages(image));
    when(ec2Client.deregisterImage(any()))
            .thenThrow(new AmazonServiceException("Something went wrong or your credentials has been expired"));
    List<CloudResource> resources = List.of(new CloudResource.Builder()
            .name(encryptedImageId)
            .type(ResourceType.AWS_ENCRYPTED_AMI)
            .build());

    underTest.deleteResources(DEFAULT_REGION, ec2Client, resources);

    verify(ec2Client, times(0)).deleteSnapshot(any());
    verify(ec2Client, times(1)).deregisterImage(any());
}
 
示例11
@Test
public void testDeleteResourcesWhenAMISnapshotDeletionFailsWithEC2Client() {
    thrown.expect(CloudConnectorException.class);

    String encryptedImageId = "ami-87654321";
    String encryptedSnapshotId = "snap-12345678";
    Image image = new Image()
            .withImageId(encryptedImageId)
            .withBlockDeviceMappings(new BlockDeviceMapping()
                    .withEbs(new EbsBlockDevice().withEncrypted(true).withSnapshotId(encryptedSnapshotId)));
    when(ec2Client.describeImages(any()))
            .thenReturn(new DescribeImagesResult().withImages(image));
    when(ec2Client.deleteSnapshot(any()))
            .thenThrow(new AmazonServiceException("Something went wrong or your credentials has been expired"));
    List<CloudResource> resources = List.of(new CloudResource.Builder()
            .name(encryptedImageId)
            .type(ResourceType.AWS_ENCRYPTED_AMI)
            .build());

    underTest.deleteResources(DEFAULT_REGION, ec2Client, resources);

    verify(ec2Client, times(1)).deregisterImage(any());
    verify(ec2Client, times(1)).deleteSnapshot(any());
}
 
示例12
@Test
public void testDeleteResourcesShouldDeleteMultipleSnapshotsWhenMultipleSnapshotAreLinkedToTheAMI() {
    String encryptedImageId = "ami-87654321";
    String encryptedSnapshotId = "snap-12345678";
    String secondEncryptedSnapshotId = "snap-12345555";
    Image image = new Image()
            .withImageId(encryptedImageId)
            .withBlockDeviceMappings(
                    new BlockDeviceMapping().withDeviceName("/dev/sdb").withVirtualName("ephemeral0"),
                    new BlockDeviceMapping().withEbs(new EbsBlockDevice().withEncrypted(true).withSnapshotId(encryptedSnapshotId)),
                    new BlockDeviceMapping().withEbs(new EbsBlockDevice().withEncrypted(true).withSnapshotId(secondEncryptedSnapshotId)));
    when(ec2Client.describeImages(any()))
            .thenReturn(new DescribeImagesResult().withImages(image));

    List<CloudResource> resources = List.of(new CloudResource.Builder()
            .name(encryptedImageId)
            .type(ResourceType.AWS_ENCRYPTED_AMI)
            .build());

    underTest.deleteResources(DEFAULT_REGION, ec2Client, resources);

    verify(ec2Client, times(1)).deregisterImage(any());
    verify(ec2Client, times(2)).deleteSnapshot(any());
}
 
示例13
@Test
public void testDeleteResourcesShouldDeleteOnlyEbsDeviceMappingsWithSnapshotWhenMultipleSnapshotAndEphemeralDevicesAreLinkedToTheAMI() {
    String encryptedImageId = "ami-87654321";
    String encryptedSnapshotId = "snap-12345678";
    String secondEncryptedSnapshotId = "snap-12345555";
    Image image = new Image()
            .withImageId(encryptedImageId)
            .withBlockDeviceMappings(
                    new BlockDeviceMapping().withEbs(new EbsBlockDevice().withEncrypted(true).withSnapshotId(encryptedSnapshotId)),
                    new BlockDeviceMapping().withEbs(new EbsBlockDevice().withEncrypted(true).withSnapshotId(secondEncryptedSnapshotId)),
                    new BlockDeviceMapping().withDeviceName("/dev/sdb").withVirtualName("ephemeral0"),
                    new BlockDeviceMapping().withDeviceName("/dev/sdc").withVirtualName("ephemeral1"));
    when(ec2Client.describeImages(any()))
            .thenReturn(new DescribeImagesResult().withImages(image));

    List<CloudResource> resources = List.of(new CloudResource.Builder()
            .name(encryptedImageId)
            .type(ResourceType.AWS_ENCRYPTED_AMI)
            .build());

    underTest.deleteResources(DEFAULT_REGION, ec2Client, resources);

    verify(ec2Client, times(1)).deregisterImage(any());
    verify(ec2Client, times(2)).deleteSnapshot(any());
}
 
示例14
/**
 * Describe Images.
 *
  * @return list of Images
 */
protected final List<Image> describeImages() {

    DescribeImagesRequest request = new DescribeImagesRequest();
    request.withImageIds("ami-12345678");
    DescribeImagesResult result = amazonEC2Client
            .describeImages(request);
    List<Image> instanceList = new ArrayList<Image>();
    if (result.getImages().size() > 0) {
     Assert.assertTrue(result.getImages().size() > 0);

     for (Image reservation : result.getImages()) {
     	instanceList.add(reservation);
	
       
     }
    }
    return instanceList;
}
 
示例15
/**
 * Calls DescribeImagess on the AWS EC2 Client returning all images that match the supplied predicate and attempting
 * to push down certain predicates (namely queries for specific volumes) to EC2.
 *
 * @note Because of the large number of public AMIs we also support using a default 'owner' filter if your query doesn't
 * filter on owner itself. You can set this using an env variable on your Lambda function defined by DEFAULT_OWNER_ENV.
 * @See TableProvider
 */
@Override
public void readWithConstraint(BlockSpiller spiller, ReadRecordsRequest recordsRequest, QueryStatusChecker queryStatusChecker)
{
    DescribeImagesRequest request = new DescribeImagesRequest();

    ValueSet idConstraint = recordsRequest.getConstraints().getSummary().get("id");
    ValueSet ownerConstraint = recordsRequest.getConstraints().getSummary().get("owner");
    if (idConstraint != null && idConstraint.isSingleValue()) {
        request.setImageIds(Collections.singletonList(idConstraint.getSingleValue().toString()));
    }
    else if (ownerConstraint != null && ownerConstraint.isSingleValue()) {
        request.setOwners(Collections.singletonList(ownerConstraint.getSingleValue().toString()));
    }
    else if (DEFAULT_OWNER != null) {
        request.setOwners(Collections.singletonList(DEFAULT_OWNER));
    }
    else {
        throw new RuntimeException("A default owner account must be set or the query must have owner" +
                "in the where clause with exactly 1 value otherwise results may be too big.");
    }

    DescribeImagesResult response = ec2.describeImages(request);

    int count = 0;
    for (Image next : response.getImages()) {
        if (count++ > MAX_IMAGES) {
            throw new RuntimeException("Too many images returned, add an owner or id filter.");
        }
        instanceToRow(next, spiller);
    }
}
 
示例16
/**
 * This method requests existing AMI details from AWS.
 * The method only requests the AMIs owned by the accessing AWS account.
 * @return List of AMIs
 */
private List<Image> getAMIListFromAWS() {
    DescribeImagesRequest request = new DescribeImagesRequest();
    request.withOwners("self");
    DescribeImagesResult result = amazonEC2.describeImages(request);
    return result.getImages();
}
 
示例17
/**
 *  This method will retrieve the instance username that is used to log into the instance via ssh.
 *  E.g Ubuntu instance has username ubuntu
 *  CentOS instance has username centos
 *  The username must be present in the ami as a TAG with key USERNAME.
 *
 * @param region The aws region where instance is located
 * @param instanceId ID value for the instance
 * @return The username extracted from the TAG
 */
public Optional<String> getInstanceUserName(String region, String instanceId) {

    final AmazonEC2 amazonEC2 = AmazonEC2ClientBuilder.standard()
            .withCredentials(new PropertiesFileCredentialsProvider(configFilePath.toString()))
            .withRegion(region)
            .build();

    List<String> instanceIds = new ArrayList<>();
    instanceIds.add(instanceId);
    DescribeInstancesRequest request = new DescribeInstancesRequest();
    request.setInstanceIds(instanceIds);
    DescribeInstancesResult result = amazonEC2.describeInstances(request);
    //Get instance id from the results
    Optional<String> imageId = result.getReservations().stream()
            .flatMap(reservation -> reservation.getInstances().stream())
            .findFirst()
            .map(Instance::getImageId);

    if (imageId.isPresent()) {
        List<String> imageIds = new ArrayList<>();
        imageIds.add(imageId.get());
        //get ami from the instance ID
        DescribeImagesRequest imageReq = new DescribeImagesRequest();
        imageReq.setImageIds(imageIds);
        //Get the Tag containing the username from the ami
        DescribeImagesResult describeImagesResult = amazonEC2.describeImages(imageReq);
        Optional<String> userName = describeImagesResult.getImages().stream()
                .flatMap(image -> image.getTags().stream())
                .filter(tag -> USERNAME_ENTRY.equals(tag.getKey()))
                .findFirst()
                .map(Tag::getValue);
        return userName;
    }
    return Optional.empty();
}
 
示例18
public void createDescribeImagesResult(String... imageIds) {
    Collection<Image> images = new ArrayList<Image>();
    for (int i = 0; i < imageIds.length; i++) {
        images.add(new Image().withImageId(imageIds[i]));
    }
    DescribeImagesResult imagesResult = new DescribeImagesResult()
            .withImages(images);
    doReturn(imagesResult).when(ec2)
            .describeImages(any(DescribeImagesRequest.class));
}
 
示例19
private Optional<Image> getAmiFromEC2Api(final AmazonEC2Client ec2Client, final String imageId) {
    try {
        final DescribeImagesResult response = ec2Client.describeImages(new DescribeImagesRequest().withImageIds(imageId));

        return ofNullable(response)
                .map(DescribeImagesResult::getImages)
                .map(List::stream)
                .flatMap(Stream::findFirst);

    } catch (final AmazonClientException e) {
        log.warn("Could not describe image " + imageId, e);
        return empty();
    }
}
 
示例20
private Optional<Image> getAmi(@Nonnull final EC2InstanceContext context) {
    final Optional<String> amiId = context.getAmiId();
    try {
        return amiId
                .map(id -> context
                        .getClient(AmazonEC2Client.class)
                        .describeImages(new DescribeImagesRequest().withImageIds(id)))
                .map(DescribeImagesResult::getImages)
                .flatMap(images -> images.stream().findFirst());
    } catch (final AmazonClientException e) {
        log.warn("Could not get AMI of: " + amiId.get(), e);
        return empty();
    }
}
 
示例21
public Image describeImage(AwsProcessClient awsProcessClient, String imageId) {
    DescribeImagesRequest request = new DescribeImagesRequest();
    request.withImageIds(imageId);
    DescribeImagesResult result = awsProcessClient.getEc2Client().describeImages(request);
    List<Image> images = result.getImages();

    if (images.isEmpty()) {
        return null;
    }

    return images.get(0);
}
 
示例22
private String getRootDeviceName(AuthenticatedContext ac, CloudStack cloudStack) {
    AmazonEC2Client ec2Client = new AuthenticatedContextView(ac).getAmazonEC2Client();
    DescribeImagesResult images = ec2Client.describeImages(new DescribeImagesRequest().withImageIds(cloudStack.getImage().getImageName()));
    if (images.getImages().isEmpty()) {
        throw new CloudConnectorException(String.format("AMI is not available: '%s'.", cloudStack.getImage().getImageName()));
    }
    Image image = images.getImages().get(0);
    if (image == null) {
        throw new CloudConnectorException(String.format("Couldn't describe AMI '%s'.", cloudStack.getImage().getImageName()));
    }
    return image.getRootDeviceName();
}
 
示例23
/**
 * Describe all available AMIs within aws-mock.
 *
 * @return a list of AMIs
 */
public static List<Image> describeAllImages() {
    // pass any credentials as aws-mock does not authenticate them at all
    AWSCredentials credentials = new BasicAWSCredentials("foo", "bar");
    AmazonEC2Client amazonEC2Client = new AmazonEC2Client(credentials);

    // the mock endpoint for ec2 which runs on your computer
    String ec2Endpoint = "http://localhost:8000/aws-mock/ec2-endpoint/";
    amazonEC2Client.setEndpoint(ec2Endpoint);

    // describe all AMIs in aws-mock.
    DescribeImagesResult result = amazonEC2Client.describeImages();

    return result.getImages();
}
 
示例24
@Override
public boolean load(DescribeImagesRequest request,
        ResultCapture<DescribeImagesResult> extractor) {

    return resource.load(request, extractor);
}
 
示例25
private void setupDescribeImagesResponse() {
    when(amazonEC2Client.describeImages(any())).thenReturn(
            new DescribeImagesResult()
                    .withImages(new com.amazonaws.services.ec2.model.Image().withRootDeviceName(""))
    );
}
 
示例26
/**
 * Makes a call to the service to load this resource's attributes if they
 * are not loaded yet, and use a ResultCapture to retrieve the low-level
 * client response
 * The following request parameters will be populated from the data of this
 * <code>Image</code> resource, and any conflicting parameter value set in
 * the request will be overridden:
 * <ul>
 *   <li>
 *     <b><code>ImageIds.0</code></b>
 *         - mapped from the <code>Id</code> identifier.
 *   </li>
 * </ul>
 *
 * <p>
 *
 * @return Returns {@code true} if the resource is not yet loaded when this
 *         method was invoked, which indicates that a service call has been
 *         made to retrieve the attributes.
 * @see DescribeImagesRequest
 */
boolean load(DescribeImagesRequest request,
        ResultCapture<DescribeImagesResult> extractor);