Example usage for com.amazonaws.services.ec2.model DescribeSnapshotsResult getSnapshots

List of usage examples for com.amazonaws.services.ec2.model DescribeSnapshotsResult getSnapshots

Introduction

In this page you can find the example usage for com.amazonaws.services.ec2.model DescribeSnapshotsResult getSnapshots.

Prototype


public java.util.List<Snapshot> getSnapshots() 

Source Link

Document

Information about the snapshots.

Usage

From source file:virtualIT.java

License:Open Source License

private void createExtraSnapShot(int userId) throws Exception {

    /******************************************
     * Creating Snap Shots before detaching volume
     *//*from w  ww  . j  a  v  a  2  s .co  m*/
    System.out.println("Creating Snap Shots before detaching volume\n");
    String volumeId = mapUserExtraVolu.get(userId);
    CreateSnapshotResult snapRes = ec2
            .createSnapshot(new CreateSnapshotRequest(volumeId, "Test snapshot" + userId));
    Snapshot snap = snapRes.getSnapshot();

    System.out.println("Snapshot request sent.");
    System.out.println("Waiting for snapshot to be created");

    String snapState = snap.getState();
    System.out.println("snapState is " + snapState);

    System.out.print("Waiting for snapshot to be created");
    // Wait for the snapshot to be created
    while (snapState.equals("pending")) {
        Thread.sleep(500);
        System.out.print(".");
        DescribeSnapshotsResult describeSnapRes = ec2
                .describeSnapshots(new DescribeSnapshotsRequest().withSnapshotIds(snap.getSnapshotId()));
        snapState = describeSnapRes.getSnapshots().get(0).getState();

    }
    mapUserExtraSnap.put(userId, snap.getSnapshotId());

    System.out.println("\nSnap shot Done.");
    return;
}

From source file:virtualIT.java

License:Open Source License

private void createRootSnapShot(int userId) throws Exception {
    String volumeId = mapUserRootVol.get(userId);
    CreateSnapshotResult snapRes = ec2/*from w  w w  .j a va 2 s  . c o  m*/
            .createSnapshot(new CreateSnapshotRequest(volumeId, "Test snapshot" + userId));
    Snapshot snap = snapRes.getSnapshot();

    System.out.println("Snapshot request sent.");
    System.out.println("Waiting for snapshot to be created");

    String snapState = snap.getState();
    System.out.println("snapState is " + snapState);

    System.out.print("Waiting for snapshot to be created");
    // Wait for the snapshot to be created
    while (snapState.equals("pending")) {
        Thread.sleep(500);
        System.out.print(".");
        DescribeSnapshotsResult describeSnapRes = ec2
                .describeSnapshots(new DescribeSnapshotsRequest().withSnapshotIds(snap.getSnapshotId()));
        snapState = describeSnapRes.getSnapshots().get(0).getState();
    }
    mapUserRootSnap.put(userId, snap.getSnapshotId());

    System.out.println("\nSnap shot Done.");
    return;
}

From source file:com.axemblr.yab.YaB.java

License:Apache License

/**
 * De-register AMI and delete related snapshot
 *///from  w  w  w  .j  a  va 2s  .  c  o m
public void deleteImageAndRelatedSnapshot(String imageId) {
    client.deregisterImage(new DeregisterImageRequest().withImageId(imageId));

    final String pattern = "for " + imageId + " from vol-";
    DescribeSnapshotsResult result = client.describeSnapshots(new DescribeSnapshotsRequest());

    for (Snapshot candidate : result.getSnapshots()) {
        if (candidate.getDescription().contains(pattern)) {
            client.deleteSnapshot(new DeleteSnapshotRequest().withSnapshotId(candidate.getSnapshotId()));
        }
    }
}

From source file:com.dowdandassociates.gentoo.bootstrap.DefaultTestSnapshotProvider.java

License:Apache License

public Optional<Snapshot> get() {
    BootstrapInstanceInformation instanceInfo = bootstrapResultInformation.getInstanceInfo();
    Optional<Instance> instance = instanceInfo.getInstance();
    Optional<Volume> volume = instanceInfo.getVolume();
    Optional<Integer> exitStatus = bootstrapResultInformation.getExitStatus();

    if (!instance.isPresent()) {
        log.info("Instance is absent");
        return Optional.absent();
    }//from w  w w.j av  a  2  s  .com

    String instanceId = instance.get().getInstanceId();

    TerminateInstancesResult terminateInstancesResult = ec2Client
            .terminateInstances(new TerminateInstancesRequest().withInstanceIds(instanceId));

    if (!volume.isPresent()) {
        log.info("Volume is absent");
        return Optional.absent();
    }

    String volumeId = volume.get().getVolumeId();

    DescribeInstancesRequest describeInstancesRequest = new DescribeInstancesRequest()
            .withInstanceIds(instanceId);

    DescribeVolumesRequest describeVolumesRequest = new DescribeVolumesRequest().withVolumeIds(volumeId);
    try {
        while (true) {
            log.info("Sleeping for " + instanceSleep.get() + " ms");
            Thread.sleep(instanceSleep.get());
            DescribeInstancesResult describeInstancesResult = ec2Client
                    .describeInstances(describeInstancesRequest);
            String state = describeInstancesResult.getReservations().get(0).getInstances().get(0).getState()
                    .getName();
            log.info("Instance State = " + state);
            if ("terminated".equals(state)) {
                break;
            }
        }

        CreateSnapshotResult createSnapshotResult = ec2Client
                .createSnapshot(new CreateSnapshotRequest().withVolumeId(volumeId));

        log.info("SnapshotId = " + createSnapshotResult.getSnapshot().getSnapshotId());

        DescribeSnapshotsRequest describeSnapshotsRequest = new DescribeSnapshotsRequest()
                .withSnapshotIds(createSnapshotResult.getSnapshot().getSnapshotId());

        Snapshot snapshot;

        while (true) {
            log.info("Sleeping for " + snapshotSleep.get() + " ms");
            Thread.sleep(snapshotSleep.get());

            DescribeSnapshotsResult describeSnapshotsResult = ec2Client
                    .describeSnapshots(describeSnapshotsRequest);
            String state = describeSnapshotsResult.getSnapshots().get(0).getState();
            log.info("Snapshot State = " + state);
            if ("error".equals(state)) {
                return Optional.absent();
            }
            if ("completed".equals(state)) {
                snapshot = describeSnapshotsResult.getSnapshots().get(0);
                break;
            }
        }

        ec2Client.deleteVolume(new DeleteVolumeRequest().withVolumeId(volumeId));

        if (!exitStatus.isPresent()) {
            log.info("Exit status is not present");
            return Optional.absent();
        }

        log.info("exit status = " + exitStatus.get());

        if (0 != exitStatus.get()) {
            return Optional.absent();
        }

        return Optional.fromNullable(snapshot);
    } catch (InterruptedException e) {
        return Optional.absent();
    }
}

From source file:com.netflix.simianarmy.client.aws.AWSClient.java

License:Apache License

/**
 * Describe a set of specific EBS snapshots.
 *
 * @param snapshotIds the snapshot ids//from w  ww.jav a 2 s.  c o  m
 * @return the snapshots
 */
public List<Snapshot> describeSnapshots(String... snapshotIds) {
    if (snapshotIds == null || snapshotIds.length == 0) {
        LOGGER.info(String.format("Getting all EBS snapshots in region %s.", region));
    } else {
        LOGGER.info(
                String.format("Getting EBS snapshotIds for %d ids in region %s.", snapshotIds.length, region));
    }

    AmazonEC2 ec2Client = ec2Client();
    DescribeSnapshotsRequest request = new DescribeSnapshotsRequest();
    // Set the owner id to self to avoid getting snapshots from other accounts.
    request.withOwnerIds(Arrays.<String>asList("self"));
    if (snapshotIds != null) {
        request.setSnapshotIds(Arrays.asList(snapshotIds));
    }
    DescribeSnapshotsResult result = ec2Client.describeSnapshots(request);
    List<Snapshot> snapshots = result.getSnapshots();

    LOGGER.info(String.format("Got %d EBS snapshots in region %s.", snapshots.size(), region));
    return snapshots;
}

From source file:com.pearson.eidetic.driver.MonitorMethods.java

public List<Snapshot> getAllSnapshotsOfVolume(AmazonEC2Client ec2Client, Volume vol, Integer numRetries,
        Integer maxApiRequestsPerSecond, String uniqueAwsAccountIdentifier) {

    if (ec2Client == null || vol == null) {
        // logger.error("CAN'T BE NULL!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
        return new ArrayList<>();
    }/*  www. ja v  a2s  .c  o m*/

    String volumeID = vol.getVolumeId();

    Filter filter = new Filter().withName("volume-id").withValues(volumeID);

    DescribeSnapshotsRequest describeSnapshotsRequest = new DescribeSnapshotsRequest().withOwnerIds("self")
            .withFilters(filter);
    DescribeSnapshotsResult describeSnapshotsResult = EC2ClientMethods.describeSnapshots(ec2Client,
            describeSnapshotsRequest, numRetries, maxApiRequestsPerSecond, uniqueAwsAccountIdentifier);

    List<Snapshot> snapshots = describeSnapshotsResult.getSnapshots();

    return snapshots;
}

From source file:com.pearson.eidetic.driver.threads.EideticSubThreadMethods.java

@Override
public List<Snapshot> getAllSnapshotsOfVolume(AmazonEC2Client ec2Client, Volume vol, Integer numRetries,
        Integer maxApiRequestsPerSecond, String uniqueAwsAccountIdentifier) {

    if (ec2Client == null || vol == null) {
        // logger.error("CAN'T BE NULL!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
        return new ArrayList<>();
    }//from www.ja va  2 s . c o m

    String volumeID = vol.getVolumeId();

    Filter filter = new Filter().withName("volume-id").withValues(volumeID);

    List<Snapshot> snapshots = null;
    try {

        DescribeSnapshotsRequest describeSnapshotsRequest = new DescribeSnapshotsRequest().withOwnerIds("self")
                .withFilters(filter);
        DescribeSnapshotsResult describeSnapshotsResult = EC2ClientMethods.describeSnapshots(ec2Client,
                describeSnapshotsRequest, numRetries, maxApiRequestsPerSecond, uniqueAwsAccountIdentifier);

        snapshots = describeSnapshotsResult.getSnapshots();
    } catch (Exception e) {
        logger.error("awsAccountNickname=\"" + uniqueAwsAccountIdentifier + "\"," + vol.getVolumeId()
                + System.lineSeparator() + e.toString() + System.lineSeparator()
                + StackTrace.getStringFromStackTrace(e));
    }

    return snapshots;
}

From source file:com.pearson.eidetic.driver.threads.subthreads.ErrorChecker.java

private List<Snapshot> getAllErrorSnapshots(AmazonEC2Client ec2Client) {
    Filter[] filters = new Filter[1];
    filters[0] = new Filter().withName("status").withValues("error");

    DescribeSnapshotsRequest describeSnapshotRequest = new DescribeSnapshotsRequest().withOwnerIds("self")
            .withFilters(filters);//from   w  ww.  ja v a2s .c  om
    DescribeSnapshotsResult describeSnapshotsResult = EC2ClientMethods.describeSnapshots(ec2Client,
            describeSnapshotRequest, numRetries_, maxApiRequestsPerSecond_, uniqueAwsAccountIdentifier_);

    return describeSnapshotsResult.getSnapshots();
}

From source file:com.pearson.eidetic.driver.threads.subthreads.SnapshotCleaner.java

public Boolean eideticClean(AmazonEC2Client ec2Client) {
    if (ec2Client == null) {
        return false;
    }//from   w w  w .  ja v  a  2 s  . c  om
    //See if tag has changed on vol. If 7 days old, delete with all snapshots with old tag.
    Filter[] filters = new Filter[1];
    filters[0] = new Filter().withName("tag-key").withValues("Eidetic");

    DescribeSnapshotsRequest describeSnapshotRequest = new DescribeSnapshotsRequest().withOwnerIds("self")
            .withFilters(filters);
    DescribeSnapshotsResult describeSnapshotsResult = EC2ClientMethods.describeSnapshots(ec2Client,
            describeSnapshotRequest, numRetries_, maxApiRequestsPerSecond_, uniqueAwsAccountIdentifier_);

    List<Snapshot> snapshots = describeSnapshotsResult.getSnapshots();
    for (Snapshot snapshot : snapshots) {
        int timeSinceCreation = getDaysBetweenNowAndSnapshot(snapshot);

        if (timeSinceCreation <= eideticCleanKeepDays_) {
            continue;
        }

        String volId = snapshot.getVolumeId();
        Filter[] volfilters = new Filter[1];
        volfilters[0] = new Filter().withName("volume-id").withValues(volId);
        DescribeVolumesRequest describeVolumesRequest = new DescribeVolumesRequest().withFilters(volfilters);
        DescribeVolumesResult describeVolumeResult = EC2ClientMethods.describeVolumes(ec2Client,
                describeVolumesRequest, numRetries_, maxApiRequestsPerSecond_, uniqueAwsAccountIdentifier_);

        List<Volume> volumes = describeVolumeResult.getVolumes();

        if (!volumes.isEmpty()) {

            Collection<Tag> voltags;
            try {
                voltags = getResourceTags(volumes.get(0));
            } catch (Exception e) {
                logger.info("awsAccountNickname=\"" + uniqueAwsAccountIdentifier_
                        + "\",Event=\"Error\", Error=\"error getting vol in Amnesia\", Volumes_toString=\""
                        + volumes.toString() + "\", Snapshot_id=\"" + snapshot.getSnapshotId()
                        + "\", stacktrace=\"" + e.toString() + System.lineSeparator()
                        + StackTrace.getStringFromStackTrace(e) + "\"");
                continue;
            }

            Tag voltag = null;
            for (Tag tag : voltags) {
                if ("Eidetic".equals(tag.getKey())) {
                    voltag = tag;
                    break;
                }
            }
            if (voltag == null) {
                continue;
            }

            Collection<Tag> snapshottags = getResourceTags(snapshot);
            Tag snaptag = null;
            for (Tag tag : snapshottags) {
                if ("Eidetic".equals(tag.getKey())) {
                    snaptag = tag;
                    break;
                }
            }
            if (snaptag == null) {
                continue;
            }

            try { //Checks to see if we modified tag, if it is the same tag the tag retain date m
                if (snaptag.getValue().equals(voltag.getValue())) {
                    continue;
                }
            } catch (Exception e) {
                logger.info("awsAccountNickname=\"" + uniqueAwsAccountIdentifier_
                        + "\",Event=\"Error\", Error=\"error comparing vol and snapshot tag values\", Volume_id=\""
                        + volumes.get(0).getVolumeId() + ", Snapshot_id=\"" + snapshot.getSnapshotId()
                        + "\", stacktrace=\"" + e.toString() + System.lineSeparator()
                        + StackTrace.getStringFromStackTrace(e) + "\"");
                continue;
            }

            try {
                deleteSnapshot(ec2Client, snapshot, numRetries_, maxApiRequestsPerSecond_,
                        uniqueAwsAccountIdentifier_);
            } catch (Exception e) {
                logger.error("awsAccountNickname=\"" + uniqueAwsAccountIdentifier_
                        + "\",Event=\"Error\", Error=\"error deleting snapshot\", Snapshot_id=\""
                        + snapshot.getSnapshotId() + "\", stacktrace=\"" + e.toString() + System.lineSeparator()
                        + StackTrace.getStringFromStackTrace(e) + "\"");
            }

        } else {
            //Volume doesn't exist
            if (timeSinceCreation > eideticCleanKeepDays_) {
                //See if old vol still exists. If not, if snap is $eideticCleanKeepDays_ days old, delete.
                try {
                    deleteSnapshot(ec2Client, snapshot, numRetries_, maxApiRequestsPerSecond_,
                            uniqueAwsAccountIdentifier_);
                } catch (Exception e) {
                    logger.error("awsAccountNickname=\"" + uniqueAwsAccountIdentifier_
                            + "\",Event=\"Error\", Error=\"error deleting snapshot\", Snapshot_id=\""
                            + snapshot.getSnapshotId() + "\", stacktrace=\"" + e.toString()
                            + System.lineSeparator() + StackTrace.getStringFromStackTrace(e) + "\"");
                }
            }
        }
    }

    filters = new Filter[1];
    filters[0] = new Filter().withName("tag-key").withValues("Eidetic-CopySnapshot");

    describeSnapshotRequest = new DescribeSnapshotsRequest().withOwnerIds("self").withFilters(filters);
    describeSnapshotsResult = EC2ClientMethods.describeSnapshots(ec2Client, describeSnapshotRequest,
            numRetries_, maxApiRequestsPerSecond_, uniqueAwsAccountIdentifier_);

    snapshots = describeSnapshotsResult.getSnapshots();

    for (Snapshot snapshot : snapshots) {
        int timeSinceCreation = getDaysBetweenNowAndSnapshot(snapshot);

        if (timeSinceCreation <= eideticCleanKeepDays_) {
            continue;
        }

        try {
            deleteSnapshot(ec2Client, snapshot, numRetries_, maxApiRequestsPerSecond_,
                    uniqueAwsAccountIdentifier_);
        } catch (Exception e) {
            logger.error("awsAccountNickname=\"" + uniqueAwsAccountIdentifier_
                    + "\",Event=\"Error\", Error=\"error deleting snapshot\", Snapshot_id=\""
                    + snapshot.getSnapshotId() + "\", stacktrace=\"" + e.toString() + System.lineSeparator()
                    + StackTrace.getStringFromStackTrace(e) + "\"");
        }

    }

    return true;
}

From source file:com.pearson.eidetic.driver.threads.subthreads.SnapshotCleaner.java

public Boolean allSnapshotsClean(AmazonEC2Client ec2Client) {
    if (ec2Client == null) {
        return false;
    }/*from www.  j av  a 2s.  c o m*/

    Filter[] filters2 = new Filter[1];
    filters2[0] = new Filter().withName("status").withValues("completed");

    DescribeSnapshotsRequest describeSnapshotRequest2 = new DescribeSnapshotsRequest().withOwnerIds("self")
            .withFilters(filters2);
    DescribeSnapshotsResult describeSnapshotsResult2 = EC2ClientMethods.describeSnapshots(ec2Client,
            describeSnapshotRequest2, numRetries_, maxApiRequestsPerSecond_, uniqueAwsAccountIdentifier_);
    //Delete all snaps allSnapshotCleanDays_ and older.
    List<Snapshot> snapshots2 = describeSnapshotsResult2.getSnapshots();
    for (Snapshot snapshot : snapshots2) {
        Integer timeSinceCreation = getDaysBetweenNowAndSnapshot(snapshot);
        if (timeSinceCreation > allSnapshotCleanKeepDays_) {
            try {
                deleteSnapshot(ec2Client, snapshot, numRetries_, maxApiRequestsPerSecond_,
                        uniqueAwsAccountIdentifier_);
            } catch (Exception e) {
                logger.error("awsAccountNickname=\"" + uniqueAwsAccountIdentifier_
                        + "\",Event=\"Error\", Error=\"error deleting snapshot\", Snapshot_id=\""
                        + snapshot.getSnapshotId() + "\", stacktrace=\"" + e.toString() + System.lineSeparator()
                        + StackTrace.getStringFromStackTrace(e) + "\"");
            }
        }
    }

    return true;
}