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

The following examples show how to use com.amazonaws.services.ec2.model.Image. 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: EncryptedImageCopyServiceTest.java    From cloudbreak with Apache License 2.0 6 votes vote down vote up
@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());
}
 
Example #2
Source File: AmiDetailsProviderImpl.java    From fullstop with Apache License 2.0 6 votes vote down vote up
@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();
}
 
Example #3
Source File: LifecyclePlugin.java    From fullstop with Apache License 2.0 6 votes vote down vote up
@Override
protected void process(final EC2InstanceContext context) {
    final LifecycleEntity lifecycleEntity = new LifecycleEntity();
    lifecycleEntity.setEventType(context.getEventName());
    lifecycleEntity.setEventDate(getLifecycleDate(context));
    lifecycleEntity.setAccountId(context.getAccountId());
    lifecycleEntity.setRegion(context.getRegionAsString());
    lifecycleEntity.setInstanceId(context.getInstanceId());
    context.getAmiId().ifPresent(lifecycleEntity::setImageId);
    context.getAmi().map(Image::getName).ifPresent(lifecycleEntity::setImageName);

    final Optional<ApplicationEntity> application = context.getApplicationId().map(ApplicationEntity::new);
    if (!application.isPresent()) {
        log.warn("Could not determine applicationId. Skip processing of LifecyclePlugin.");
        return;
    }

    final Optional<VersionEntity> version = context.getVersionId().map(VersionEntity::new);
    if (!version.isPresent()) {
        log.warn("Could not determine versionId. Skip processing of LifecyclePlugin.");
        return;
    }

    applicationLifecycleService.saveLifecycle(application.get(), version.get(), lifecycleEntity);
}
 
Example #4
Source File: AmiPlugin.java    From fullstop with Apache License 2.0 6 votes vote down vote up
@Override
protected void process(final EC2InstanceContext context) {

    if (!context.isTaupageAmi().orElse(false)) {
        violationSink.put(
                context.violation()
                        .withType(WRONG_AMI)
                        .withPluginFullyQualifiedClassName(AmiPlugin.class)
                        .withMetaInfo(ImmutableMap.of(
                                "ami_owner_id", context.getAmi().map(Image::getOwnerId).orElse(""),
                                "ami_id", context.getAmiId().orElse(""),
                                "ami_name", context.getAmi().map(Image::getName).orElse("")))
                        .build());
    }

}
 
Example #5
Source File: AmiProviderImplTest.java    From fullstop with Apache License 2.0 6 votes vote down vote up
@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));
}
 
Example #6
Source File: AmiProviderImplTest.java    From fullstop with Apache License 2.0 6 votes vote down vote up
@Test
public void testApplyAmiNotFound() 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(null);

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

    assertThat(result).isEmpty();

    verify(ec2InstanceContextMock).getAmiId();
    verify(ec2InstanceContextMock).getClient(eq(AmazonEC2Client.class));
    verify(amazonEC2ClientMock).describeImages(eq(describeImagesRequest));
}
 
Example #7
Source File: AmiProviderImplTest.java    From fullstop with Apache License 2.0 6 votes vote down vote up
@Test
public void testApplyAmiNotFoundWithException() 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)))
            .thenThrow(new AmazonClientException("oops, I did it again... Britney"));

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

    assertThat(result).isEmpty();

    verify(ec2InstanceContextMock).getAmiId();
    verify(ec2InstanceContextMock).getClient(eq(AmazonEC2Client.class));
    verify(amazonEC2ClientMock).describeImages(eq(describeImagesRequest));
}
 
Example #8
Source File: EncryptedImageCopyServiceTest.java    From cloudbreak with Apache License 2.0 6 votes vote down vote up
@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());
}
 
Example #9
Source File: EncryptedImageCopyServiceTest.java    From cloudbreak with Apache License 2.0 6 votes vote down vote up
@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());
}
 
Example #10
Source File: ImagesTableProviderTest.java    From aws-athena-query-federation with Apache License 2.0 6 votes vote down vote up
@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;
    });
}
 
Example #11
Source File: EncryptedImageCopyServiceTest.java    From cloudbreak with Apache License 2.0 6 votes vote down vote up
@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());
}
 
Example #12
Source File: EncryptedImageCopyServiceTest.java    From cloudbreak with Apache License 2.0 6 votes vote down vote up
@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());
}
 
Example #13
Source File: EncryptedImageCopyServiceTest.java    From cloudbreak with Apache License 2.0 6 votes vote down vote up
@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());
}
 
Example #14
Source File: EncryptedImageCopyServiceTest.java    From cloudbreak with Apache License 2.0 6 votes vote down vote up
@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());
}
 
Example #15
Source File: EncryptedImageCopyServiceTest.java    From cloudbreak with Apache License 2.0 6 votes vote down vote up
@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());
}
 
Example #16
Source File: Ec2EndpointTest.java    From aws-mock with MIT License 6 votes vote down vote up
/**
 * Test describing instances with states filter.
 */
@Test(timeout = TIMEOUT_LEVEL2)
public final void describeImagesAllTest() {
    log.info("Start describing Images with states filter test");

    List<Image> instances = describeImages();
    if(instances != null)
    {
       for (Image i : instances) {
         log.info(i.getImageId());
       }
    }
    else
    {
    	log.info("Count :" + 0);
    }
}
 
Example #17
Source File: BaseTest.java    From aws-mock with MIT License 6 votes vote down vote up
/**
 * 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;
}
 
Example #18
Source File: EC2CommunicationTest.java    From development with Apache License 2.0 6 votes vote down vote up
@Test
public void testCreateInstanceUserDataMalformedUrl() throws Exception {
    try {
        parameters.put(PropertyHandler.USERDATA_URL, new Setting(
                PropertyHandler.USERDATA_URL, "MALFORMED_URL"));
        ec2mock.createRunInstancesResult("instance2");
        ec2mock.createDescribeImagesResult("image1");
        ec2mock.createDescribeSubnetsResult("subnet-a77430d0");
        ec2mock.createDescribeSecurityGroupResult("subnet-a77430d0",
                "security_group1,security_group2");
        ec2mock.createDescribeInstancesResult("instance1", "ok", "1.2.3.4");
        Image image = ec2comm.resolveAMI("image1");
        ec2comm.createInstance(image);

        assertTrue("Exception expected", false);

    } catch (APPlatformException ape) {
        assertTrue(ape.getMessage(),
                ape.getMessage().contains("MALFORMED_URL"));
    }
}
 
Example #19
Source File: EC2CommunicationTest.java    From development with Apache License 2.0 6 votes vote down vote up
@Test
public void testCreateInstanceSecurityGroupsMultiple() throws Exception {
    parameters.put(PropertyHandler.SECURITY_GROUP_NAMES, new Setting(
            PropertyHandler.SECURITY_GROUP_NAMES,
            "security_group1, security_group2"));
    ec2mock.createRunInstancesResult("instance3");
    ec2mock.createDescribeImagesResult("image1");
    ec2mock.createDescribeSubnetsResult("subnet-a77430d0");
    ec2mock.createDescribeSecurityGroupResult("subnet-a77430d0",
            "security_group1,security_group2");
    ec2mock.createDescribeInstancesResult("instance1", "ok", "1.2.3.4");
    Image image = ec2comm.resolveAMI("image1");
    ec2comm.createInstance(image);
    String result = ph.getAWSInstanceId();
    assertEquals("instance3", result);

    ArgumentCaptor<RunInstancesRequest> arg1 = ArgumentCaptor
            .forClass(RunInstancesRequest.class);
    verify(ec2).runInstances(arg1.capture());
    RunInstancesRequest rir = arg1.getValue();
    // Network interfaces and an instance-level security groups may not be
    // specified on the same request..
    assertEquals(2, rir.getNetworkInterfaces().get(0).getGroups().size());
    // assertEquals("security_group1", rir.getSecurityGroups().get(0));
    // assertEquals("security_group2", rir.getSecurityGroups().get(1));
}
 
Example #20
Source File: AMIMapper.java    From testgrid with Apache License 2.0 6 votes vote down vote up
/**
 * This method finds out the relevant AMI-id of the AMI which matches for the infra-parameters passed.
 *
 * @param infraParameters Infrastructure parameters (of the test-plan)
 * @return AMI-id of the matching AMI
 * @throws TestGridInfrastructureException When can not find a matching AMI
 */
public String getAMIFor(Properties infraParameters) throws TestGridInfrastructureException {
    List<Image> amiList = getAMIListFromAWS();
    if (amiList.isEmpty()) {
        throw new TestGridInfrastructureException("List of AMIs is empty. Hence can not find a matching AMI.");
    }
    Properties lookupParameters = filterLookupParameters(infraParameters);

    Optional<String> amiId = findAMIForLookupParams(amiList, lookupParameters);

    if (amiId.isPresent()) {
        logger.debug(StringUtil.concatStrings("Found matching AMI. AMI-ID: ", amiId));
        return amiId.get();
    } else {
        throw new TestGridInfrastructureException("Can not find an AMI match for " +
        getPropertiesAsString(lookupParameters));
    }
}
 
Example #21
Source File: EC2CommunicationTest.java    From development with Apache License 2.0 6 votes vote down vote up
@Test
public void testCreateInstanceUserDataInvalidPath() throws Exception {
    File myFile = createUserDataFile("test123");
    try {
        URL fileUrl = myFile.toURI().toURL();
        parameters.put(PropertyHandler.USERDATA_URL, new Setting(
                PropertyHandler.USERDATA_URL, fileUrl.toString()
                        + "_notexisting"));
        ec2mock.createRunInstancesResult("instance2");
        ec2mock.createDescribeImagesResult("image1");
        ec2mock.createDescribeSubnetsResult("subnet-a77430d0");
        ec2mock.createDescribeSecurityGroupResult("subnet-a77430d0",
                "security_group1,security_group2");
        ec2mock.createDescribeInstancesResult("instance1", "ok", "1.2.3.4");
        Image image = ec2comm.resolveAMI("image1");
        ec2comm.createInstance(image);
        assertTrue("Exception expected", false);

    } catch (APPlatformException ape) {
        assertTrue("Error message not as expected", ape.getMessage()
                .contains("cannot find the file")
                || ape.getMessage().contains("No such file"));
    } finally {
        myFile.delete();
    }
}
 
Example #22
Source File: EC2Communication.java    From development with Apache License 2.0 6 votes vote down vote up
/**
 * 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);
}
 
Example #23
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 #24
Source File: AMIMapper.java    From testgrid with Apache License 2.0 5 votes vote down vote up
/**
 * 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();
}
 
Example #25
Source File: AwsCommonProcess.java    From primecloud-controller with GNU General Public License v2.0 5 votes vote down vote up
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);
}
 
Example #26
Source File: AwsStackRequestHelper.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
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();
}
 
Example #27
Source File: EncryptedImageCopyService.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
private void deleteImage(AmazonEC2Client client, CloudResource encryptedImage, Image image, String regionName) {
    LOGGER.debug("Deregister encrypted AMI: '{}', in region: '{}'", encryptedImage.getName(), regionName);
    DeregisterImageRequest deregisterImageRequest = new DeregisterImageRequest().withImageId(encryptedImage.getName());
    client.deregisterImage(deregisterImageRequest);

    image.getBlockDeviceMappings()
            .stream()
            .filter(deviceMapping -> deviceMapping.getEbs() != null && isNotEmpty(deviceMapping.getEbs().getSnapshotId()))
            .forEach(deviceMapping -> deleteSnapshot(client, deviceMapping, encryptedImage, regionName));
}
 
Example #28
Source File: EC2CommunicationTest.java    From development with Apache License 2.0 5 votes vote down vote up
@Test(expected = APPlatformException.class)
public void testCreateInstanceInvalid() throws Exception {
    // Missing instance id
    ec2mock.createRunInstancesResult();
    ec2mock.createDescribeImagesResult("image1");
    ec2mock.createDescribeSubnetsResult("subnet-a77430d0");
    ec2mock.createDescribeSecurityGroupResult("subnet-a77430d0",
            "security_group1, security_group2");
    Image image = ec2comm.resolveAMI("image1");
    ec2comm.createInstance(image);
}
 
Example #29
Source File: EC2CommunicationTest.java    From development with Apache License 2.0 5 votes vote down vote up
@Test
public void testCreateInstance() throws Exception {
    ec2mock.createRunInstancesResult("instance1");
    ec2mock.createDescribeImagesResult("image1");
    ec2mock.createDescribeSubnetsResult("subnet-a77430d0");
    ec2mock.createDescribeSecurityGroupResult("subnet-a77430d0",
            "security_group1,security_group2");
    ec2mock.createDescribeInstancesResult("instance1", "ok", "1.2.3.4");
    Image image = ec2comm.resolveAMI("image1");
    ec2comm.createInstance(image);
    String result = ph.getAWSInstanceId();
    assertEquals("instance1", result);
    ArgumentCaptor<RunInstancesRequest> arg1 = ArgumentCaptor
            .forClass(RunInstancesRequest.class);
    verify(ec2).runInstances(arg1.capture());
    RunInstancesRequest rir = arg1.getValue();
    assertEquals("image1", rir.getImageId());
    assertEquals("type1", rir.getInstanceType());
    assertEquals("key_pair", rir.getKeyName());
    assertEquals(1, rir.getMinCount().intValue());
    assertEquals(1, rir.getMaxCount().intValue());

    ArgumentCaptor<CreateTagsRequest> arg2 = ArgumentCaptor
            .forClass(CreateTagsRequest.class);
    verify(ec2).createTags(arg2.capture());
    CreateTagsRequest ctr = arg2.getValue();
    for (Tag t : ctr.getTags()) {
        if (t.getKey().equalsIgnoreCase("Name")) {
            assertEquals("name1", t.getValue());
        } else if (t.getKey().equalsIgnoreCase("SubscriptionId")) {
            assertEquals("subId", t.getValue());
        } else if (t.getKey().equalsIgnoreCase("OrganizationId")) {
            assertEquals("orgId", t.getValue());
        }
    }

    parameters.put("USERDATA_URL", new Setting("USERDATA_URL", "userdata"));

}
 
Example #30
Source File: EC2CommunicationTest.java    From development with Apache License 2.0 5 votes vote down vote up
@Test
public void testCreateInstanceUserData() throws Exception {
    String userData = "line1\nline2\n";
    String userDataBase64 = Base64.encodeBase64String(userData.getBytes());
    File myFile = createUserDataFile(userData);
    try {
        URL fileUrl = myFile.toURI().toURL();
        parameters.put(PropertyHandler.USERDATA_URL, new Setting(
                PropertyHandler.USERDATA_URL, fileUrl.toString()));
        ec2mock.createRunInstancesResult("instance2");
        ec2mock.createDescribeImagesResult("image1");
        ec2mock.createDescribeSubnetsResult("subnet-a77430d0");
        ec2mock.createDescribeSecurityGroupResult("subnet-a77430d0",
                "security_group1,security_group2");
        ec2mock.createDescribeInstancesResult("instance1", "ok", "1.2.3.4");
        Image image = ec2comm.resolveAMI("image1");

        ec2comm.createInstance(image);
        String result = ph.getAWSInstanceId();
        assertEquals("instance2", result);
        ArgumentCaptor<RunInstancesRequest> arg1 = ArgumentCaptor
                .forClass(RunInstancesRequest.class);
        verify(ec2).runInstances(arg1.capture());
        RunInstancesRequest rir = arg1.getValue();
        assertEquals(userDataBase64, rir.getUserData());
    } finally {
        myFile.delete();
    }
}