Example usage for com.amazonaws.services.ec2.model BlockDeviceMapping setDeviceName

List of usage examples for com.amazonaws.services.ec2.model BlockDeviceMapping setDeviceName

Introduction

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

Prototype


public void setDeviceName(String deviceName) 

Source Link

Document

The device name (for example, /dev/sdh or xvdh).

Usage

From source file:InlineGettingStartedCodeApp.java

License:Open Source License

/**
 * @param args//from www  .  ja  v  a  2  s .  c  om
 */
public static void main(String[] args) {
    //============================================================================================//
    //=============================== Submitting a Request =======================================//
    //============================================================================================//

    // Create the AmazonEC2Client object so we can call various APIs.
    AmazonEC2 ec2 = new AmazonEC2Client(new ClasspathPropertiesFileCredentialsProvider());
    Region usEast1 = Region.getRegion(Regions.US_EAST_1);
    ec2.setRegion(usEast1);

    // Initializes a Spot Instance Request
    RequestSpotInstancesRequest requestRequest = new RequestSpotInstancesRequest();

    //*************************** Required Parameters Settings ************************//
    // Request 1 x t1.micro instance with a bid price of $0.03.
    requestRequest.setSpotPrice("0.03");
    requestRequest.setInstanceCount(Integer.valueOf(1));

    // Setup the specifications of the launch. This includes the instance type (e.g. t1.micro)
    // and the latest Amazon Linux AMI id available. Note, you should always use the latest
    // Amazon Linux AMI id or another of your choosing.
    LaunchSpecification launchSpecification = new LaunchSpecification();
    launchSpecification.setImageId("ami-700e4a19");
    launchSpecification.setInstanceType("t1.micro");

    // Add the security group to the request.
    ArrayList<String> securityGroups = new ArrayList<String>();
    securityGroups.add("ForAssignment2");
    launchSpecification.setSecurityGroups(securityGroups);

    //*************************** Bid Type Settings ************************//
    // Set the type of the bid to persistent.
    requestRequest.setType("persistent");

    //*************************** Valid From/To Settings ************************//
    // Set the valid start time to be two minutes from now.
    Calendar from = Calendar.getInstance();
    from.add(Calendar.MINUTE, 2);
    requestRequest.setValidFrom(from.getTime());

    // Set the valid end time to be two minutes and two hours from now.
    Calendar until = (Calendar) from.clone();
    until.add(Calendar.HOUR, 2);
    requestRequest.setValidUntil(until.getTime());

    //*************************** Launch Group Settings ************************//
    // Set the launch group.
    requestRequest.setLaunchGroup("ADVANCED-DEMO-LAUNCH-GROUP");

    //*************************** Availability Zone Group Settings ************************//
    // Set the availability zone group.
    requestRequest.setAvailabilityZoneGroup("ADVANCED-DEMO-AZ-GROUP");

    //*************************** Add the block device mapping ************************//

    // Goal: Setup block device mappings to ensure that we will not delete
    // the root partition on termination.

    // Create the block device mapping to describe the root partition.
    BlockDeviceMapping blockDeviceMapping = new BlockDeviceMapping();
    blockDeviceMapping.setDeviceName("/dev/sda1");

    // Set the delete on termination flag to false.
    EbsBlockDevice ebs = new EbsBlockDevice();
    ebs.setDeleteOnTermination(Boolean.FALSE);
    blockDeviceMapping.setEbs(ebs);

    // Add the block device mapping to the block list.
    ArrayList<BlockDeviceMapping> blockList = new ArrayList<BlockDeviceMapping>();
    blockList.add(blockDeviceMapping);

    // Set the block device mapping configuration in the launch specifications.
    launchSpecification.setBlockDeviceMappings(blockList);

    //*************************** Add the availability zone ************************//
    // Setup the availability zone to use. Note we could retrieve the availability
    // zones using the ec2.describeAvailabilityZones() API. For this demo we will just use
    // us-east-1b.
    SpotPlacement placement = new SpotPlacement("us-east-1b");
    launchSpecification.setPlacement(placement);

    //*************************** Add the placement group ************************//
    // Setup the placement group to use with whatever name you desire.
    // For this demo we will just use "ADVANCED-DEMO-PLACEMENT-GROUP".
    // Note: We have commented this out, because we are not leveraging cc1.4xlarge or
    // cg1.4xlarge in this example.
    /*
    SpotPlacement pg = new SpotPlacement();
    pg.setGroupName("ADVANCED-DEMO-PLACEMENT-GROUP");
    launchSpecification.setPlacement(pg);
    */

    //*************************** Add the launch specification ************************//
    // Add the launch specification.
    requestRequest.setLaunchSpecification(launchSpecification);

    //============================================================================================//
    //=========================== Getting the Request ID from the Request ========================//
    //============================================================================================//

    // Call the RequestSpotInstance API.
    RequestSpotInstancesResult requestResult = ec2.requestSpotInstances(requestRequest);
    List<SpotInstanceRequest> requestResponses = requestResult.getSpotInstanceRequests();

    // Setup an arraylist to collect all of the request ids we want to watch hit the running
    // state.
    ArrayList<String> spotInstanceRequestIds = new ArrayList<String>();

    // Add all of the request ids to the hashset, so we can determine when they hit the
    // active state.
    for (SpotInstanceRequest requestResponse : requestResponses) {
        System.out.println("Created Spot Request: " + requestResponse.getSpotInstanceRequestId());
        spotInstanceRequestIds.add(requestResponse.getSpotInstanceRequestId());
    }

    //============================================================================================//
    //=========================== Determining the State of the Spot Request ======================//
    //============================================================================================//

    // Create a variable that will track whether there are any requests still in the open state.
    boolean anyOpen;

    // Initialize variables.
    ArrayList<String> instanceIds = new ArrayList<String>();

    do {
        // Create the describeRequest with tall of the request id to monitor (e.g. that we started).
        DescribeSpotInstanceRequestsRequest describeRequest = new DescribeSpotInstanceRequestsRequest();
        describeRequest.setSpotInstanceRequestIds(spotInstanceRequestIds);

        // Initialize the anyOpen variable to false ??? which assumes there are no requests open unless
        // we find one that is still open.
        anyOpen = false;

        try {
            // Retrieve all of the requests we want to monitor.
            DescribeSpotInstanceRequestsResult describeResult = ec2
                    .describeSpotInstanceRequests(describeRequest);
            List<SpotInstanceRequest> describeResponses = describeResult.getSpotInstanceRequests();

            // Look through each request and determine if they are all in the active state.
            for (SpotInstanceRequest describeResponse : describeResponses) {
                // If the state is open, it hasn't changed since we attempted to request it.
                // There is the potential for it to transition almost immediately to closed or
                // cancelled so we compare against open instead of active.
                if (describeResponse.getState().equals("open")) {
                    anyOpen = true;
                    break;
                }

                // Add the instance id to the list we will eventually terminate.
                instanceIds.add(describeResponse.getInstanceId());
            }
        } catch (AmazonServiceException e) {
            // If we have an exception, ensure we don't break out of the loop.
            // This prevents the scenario where there was blip on the wire.
            anyOpen = true;
        }

        try {
            // Sleep for 60 seconds.
            Thread.sleep(60 * 1000);
        } catch (Exception e) {
            // Do nothing because it woke up early.
        }
    } while (anyOpen);

    //============================================================================================//
    //====================================== Canceling the Request ==============================//
    //============================================================================================//

    try {
        // Cancel requests.
        CancelSpotInstanceRequestsRequest cancelRequest = new CancelSpotInstanceRequestsRequest(
                spotInstanceRequestIds);
        ec2.cancelSpotInstanceRequests(cancelRequest);
    } catch (AmazonServiceException e) {
        // Write out any exceptions that may have occurred.
        System.out.println("Error cancelling instances");
        System.out.println("Caught Exception: " + e.getMessage());
        System.out.println("Reponse Status Code: " + e.getStatusCode());
        System.out.println("Error Code: " + e.getErrorCode());
        System.out.println("Request ID: " + e.getRequestId());
    }

    //============================================================================================//
    //=================================== Terminating any Instances ==============================//
    //============================================================================================//
    try {
        // Terminate instances.
        TerminateInstancesRequest terminateRequest = new TerminateInstancesRequest(instanceIds);
        ec2.terminateInstances(terminateRequest);
    } catch (AmazonServiceException e) {
        // Write out any exceptions that may have occurred.
        System.out.println("Error terminating instances");
        System.out.println("Caught Exception: " + e.getMessage());
        System.out.println("Reponse Status Code: " + e.getStatusCode());
        System.out.println("Error Code: " + e.getErrorCode());
        System.out.println("Request ID: " + e.getRequestId());
    }

}

From source file:advanced.InlineGettingStartedCodeSampleApp.java

License:Open Source License

/**
 * @param args/*from  w  w w.  ja  va  2 s .  c  o m*/
 */
public static void main(String[] args) {
    //============================================================================================//
    //=============================== Submitting a Request =======================================// 
    //============================================================================================//

    // Retrieves the credentials from an AWSCredentials.properties file.
    AWSCredentials credentials = null;
    try {
        credentials = new PropertiesCredentials(
                InlineTaggingCodeSampleApp.class.getResourceAsStream("AwsCredentials.properties"));
    } catch (IOException e1) {
        System.out.println("Credentials were not properly entered into AwsCredentials.properties.");
        System.out.println(e1.getMessage());
        System.exit(-1);
    }

    // Create the AmazonEC2Client object so we can call various APIs.
    AmazonEC2 ec2 = new AmazonEC2Client(credentials);

    // Initializes a Spot Instance Request
    RequestSpotInstancesRequest requestRequest = new RequestSpotInstancesRequest();

    //*************************** Required Parameters Settings ************************// 
    // Request 1 x t1.micro instance with a bid price of $0.03. 
    requestRequest.setSpotPrice("0.03");
    requestRequest.setInstanceCount(Integer.valueOf(1));

    // Setup the specifications of the launch. This includes the instance type (e.g. t1.micro)
    // and the latest Amazon Linux AMI id available. Note, you should always use the latest 
    // Amazon Linux AMI id or another of your choosing.
    LaunchSpecification launchSpecification = new LaunchSpecification();
    launchSpecification.setImageId("ami-8c1fece5");
    launchSpecification.setInstanceType("t1.micro");

    // Add the security group to the request.
    ArrayList<String> securityGroups = new ArrayList<String>();
    securityGroups.add("GettingStartedGroup");
    launchSpecification.setSecurityGroups(securityGroups);

    //*************************** Bid Type Settings ************************// 
    // Set the type of the bid to persistent.
    requestRequest.setType("persistent");

    //*************************** Valid From/To Settings ************************// 
    // Set the valid start time to be two minutes from now.
    Calendar from = Calendar.getInstance();
    from.add(Calendar.MINUTE, 2);
    requestRequest.setValidFrom(from.getTime());

    // Set the valid end time to be two minutes and two hours from now.
    Calendar until = (Calendar) from.clone();
    until.add(Calendar.HOUR, 2);
    requestRequest.setValidUntil(until.getTime());

    //*************************** Launch Group Settings ************************// 
    // Set the launch group.
    requestRequest.setLaunchGroup("ADVANCED-DEMO-LAUNCH-GROUP");

    //*************************** Availability Zone Group Settings ************************// 
    // Set the availability zone group.
    requestRequest.setAvailabilityZoneGroup("ADVANCED-DEMO-AZ-GROUP");

    //*************************** Add the block device mapping ************************// 

    // Goal: Setup block device mappings to ensure that we will not delete
    // the root partition on termination.

    // Create the block device mapping to describe the root partition.
    BlockDeviceMapping blockDeviceMapping = new BlockDeviceMapping();
    blockDeviceMapping.setDeviceName("/dev/sda1");

    // Set the delete on termination flag to false.
    EbsBlockDevice ebs = new EbsBlockDevice();
    ebs.setDeleteOnTermination(Boolean.FALSE);
    blockDeviceMapping.setEbs(ebs);

    // Add the block device mapping to the block list.
    ArrayList<BlockDeviceMapping> blockList = new ArrayList<BlockDeviceMapping>();
    blockList.add(blockDeviceMapping);

    // Set the block device mapping configuration in the launch specifications.
    launchSpecification.setBlockDeviceMappings(blockList);

    //*************************** Add the availability zone ************************// 
    // Setup the availability zone to use. Note we could retrieve the availability 
    // zones using the ec2.describeAvailabilityZones() API. For this demo we will just use
    // us-east-1b.
    SpotPlacement placement = new SpotPlacement("us-east-1b");
    launchSpecification.setPlacement(placement);

    //*************************** Add the placement group ************************// 
    // Setup the placement group to use with whatever name you desire.
    // For this demo we will just use "ADVANCED-DEMO-PLACEMENT-GROUP".
    // Note: We have commented this out, because we are not leveraging cc1.4xlarge or
    // cg1.4xlarge in this example.
    /*
    SpotPlacement pg = new SpotPlacement();
    pg.setGroupName("ADVANCED-DEMO-PLACEMENT-GROUP");
    launchSpecification.setPlacement(pg);
    */

    //*************************** Add the launch specification ************************// 
    // Add the launch specification.
    requestRequest.setLaunchSpecification(launchSpecification);

    //============================================================================================//
    //=========================== Getting the Request ID from the Request ========================// 
    //============================================================================================//

    // Call the RequestSpotInstance API. 
    RequestSpotInstancesResult requestResult = ec2.requestSpotInstances(requestRequest);
    List<SpotInstanceRequest> requestResponses = requestResult.getSpotInstanceRequests();

    // Setup an arraylist to collect all of the request ids we want to watch hit the running
    // state.
    ArrayList<String> spotInstanceRequestIds = new ArrayList<String>();

    // Add all of the request ids to the hashset, so we can determine when they hit the 
    // active state.
    for (SpotInstanceRequest requestResponse : requestResponses) {
        System.out.println("Created Spot Request: " + requestResponse.getSpotInstanceRequestId());
        spotInstanceRequestIds.add(requestResponse.getSpotInstanceRequestId());
    }

    //============================================================================================//
    //=========================== Determining the State of the Spot Request ======================// 
    //============================================================================================//

    // Create a variable that will track whether there are any requests still in the open state.
    boolean anyOpen;

    // Initialize variables.
    ArrayList<String> instanceIds = new ArrayList<String>();

    do {
        // Create the describeRequest with tall of the request id to monitor (e.g. that we started).
        DescribeSpotInstanceRequestsRequest describeRequest = new DescribeSpotInstanceRequestsRequest();
        describeRequest.setSpotInstanceRequestIds(spotInstanceRequestIds);

        // Initialize the anyOpen variable to false  which assumes there are no requests open unless
        // we find one that is still open.
        anyOpen = false;

        try {
            // Retrieve all of the requests we want to monitor. 
            DescribeSpotInstanceRequestsResult describeResult = ec2
                    .describeSpotInstanceRequests(describeRequest);
            List<SpotInstanceRequest> describeResponses = describeResult.getSpotInstanceRequests();

            // Look through each request and determine if they are all in the active state.
            for (SpotInstanceRequest describeResponse : describeResponses) {
                // If the state is open, it hasn't changed since we attempted to request it.
                // There is the potential for it to transition almost immediately to closed or
                // cancelled so we compare against open instead of active.
                if (describeResponse.getState().equals("open")) {
                    anyOpen = true;
                    break;
                }

                // Add the instance id to the list we will eventually terminate.
                instanceIds.add(describeResponse.getInstanceId());
            }
        } catch (AmazonServiceException e) {
            // If we have an exception, ensure we don't break out of the loop.
            // This prevents the scenario where there was blip on the wire.
            anyOpen = true;
        }

        try {
            // Sleep for 60 seconds.
            Thread.sleep(60 * 1000);
        } catch (Exception e) {
            // Do nothing because it woke up early.
        }
    } while (anyOpen);

    //============================================================================================//
    //====================================== Canceling the Request ==============================// 
    //============================================================================================//

    try {
        // Cancel requests.
        CancelSpotInstanceRequestsRequest cancelRequest = new CancelSpotInstanceRequestsRequest(
                spotInstanceRequestIds);
        ec2.cancelSpotInstanceRequests(cancelRequest);
    } catch (AmazonServiceException e) {
        // Write out any exceptions that may have occurred.
        System.out.println("Error cancelling instances");
        System.out.println("Caught Exception: " + e.getMessage());
        System.out.println("Reponse Status Code: " + e.getStatusCode());
        System.out.println("Error Code: " + e.getErrorCode());
        System.out.println("Request ID: " + e.getRequestId());
    }

    //============================================================================================//
    //=================================== Terminating any Instances ==============================// 
    //============================================================================================//
    try {
        // Terminate instances.
        TerminateInstancesRequest terminateRequest = new TerminateInstancesRequest(instanceIds);
        ec2.terminateInstances(terminateRequest);
    } catch (AmazonServiceException e) {
        // Write out any exceptions that may have occurred.
        System.out.println("Error terminating instances");
        System.out.println("Caught Exception: " + e.getMessage());
        System.out.println("Reponse Status Code: " + e.getStatusCode());
        System.out.println("Error Code: " + e.getErrorCode());
        System.out.println("Request ID: " + e.getRequestId());
    }

}

From source file:advanced.Requests.java

License:Open Source License

/**
 * The submit method will create 1 x one-time t1.micro request with a maximum bid
 * price of $0.03 using the Amazon Linux AMI. 
 * /* w ww.  ja v  a2  s  .  c  o m*/
 * Note the AMI id may change after the release of this code sample, and it is important 
 * to use the latest. You can find the latest version by logging into the AWS Management 
 * console, and attempting to perform a launch. You will be presented with AMI options, 
 * one of which will be Amazon Linux. Simply use that AMI id.
 */
public void submitRequests() {
    //==========================================================================//
    //================= Submit a Spot Instance Request =====================//
    //==========================================================================//

    // Initializes a Spot Instance Request
    RequestSpotInstancesRequest requestRequest = new RequestSpotInstancesRequest();

    // Request 1 x t1.micro instance with a bid price of $0.03. 
    requestRequest.setSpotPrice(bidPrice);
    requestRequest.setInstanceCount(Integer.valueOf(1));

    // Setup the specifications of the launch. This includes the instance type (e.g. t1.micro)
    // and the latest Amazon Linux AMI id available. Note, you should always use the latest 
    // Amazon Linux AMI id or another of your choosing.
    LaunchSpecification launchSpecification = new LaunchSpecification();
    launchSpecification.setImageId(amiID);
    launchSpecification.setInstanceType(instanceType);

    // Add the security group to the request.
    ArrayList<String> securityGroups = new ArrayList<String>();
    securityGroups.add(securityGroup);
    launchSpecification.setSecurityGroups(securityGroups);

    // If a placement group has been set, then we will use it in the request.
    if (placementGroupName != null && !placementGroupName.equals("")) {
        // Setup the placement group to use with whatever name you desire.
        SpotPlacement placement = new SpotPlacement();
        placement.setGroupName(placementGroupName);
        launchSpecification.setPlacement(placement);
    }

    // Check to see if we need to set the availability zone name.
    if (availabilityZoneName != null && !availabilityZoneName.equals("")) {
        // Setup the availability zone to use. Note we could retrieve the availability 
        // zones using the ec2.describeAvailabilityZones() API. 
        SpotPlacement placement = new SpotPlacement(availabilityZoneName);
        launchSpecification.setPlacement(placement);
    }

    if (availabilityZoneGroupName != null && !availabilityZoneGroupName.equals("")) {
        // Set the availability zone group.
        requestRequest.setAvailabilityZoneGroup(availabilityZoneGroupName);
    }

    // Check to see if we need to set the launch group.
    if (launchGroupName != null && !launchGroupName.equals("")) {
        // Set the availability launch group.
        requestRequest.setLaunchGroup(launchGroupName);
    }

    // Check to see if we need to set the valid from option.
    if (validFrom != null) {
        requestRequest.setValidFrom(validFrom);
    }

    // Check to see if we need to set the valid until option.
    if (validTo != null) {
        requestRequest.setValidUntil(validFrom);
    }

    // Check to see if we need to set the request type.
    if (requestType != null && !requestType.equals("")) {
        // Set the type of the bid.
        requestRequest.setType(requestType);
    }

    // If we should delete the EBS boot partition on termination.
    if (!deleteOnTermination) {
        // Create the block device mapping to describe the root partition.
        BlockDeviceMapping blockDeviceMapping = new BlockDeviceMapping();
        blockDeviceMapping.setDeviceName("/dev/sda1");

        // Set the delete on termination flag to false.
        EbsBlockDevice ebs = new EbsBlockDevice();
        ebs.setDeleteOnTermination(Boolean.FALSE);
        blockDeviceMapping.setEbs(ebs);

        // Add the block device mapping to the block list.
        ArrayList<BlockDeviceMapping> blockList = new ArrayList<BlockDeviceMapping>();
        blockList.add(blockDeviceMapping);

        // Set the block device mapping configuration in the launch specifications.
        launchSpecification.setBlockDeviceMappings(blockList);
    }

    // Add the launch specifications to the request.
    requestRequest.setLaunchSpecification(launchSpecification);

    // Call the RequestSpotInstance API. 
    RequestSpotInstancesResult requestResult = ec2.requestSpotInstances(requestRequest);
    List<SpotInstanceRequest> requestResponses = requestResult.getSpotInstanceRequests();

    // Setup an arraylist to collect all of the request ids we want to watch hit the running
    // state.
    spotInstanceRequestIds = new ArrayList<String>();

    // Add all of the request ids to the hashset, so we can determine when they hit the 
    // active state.
    for (SpotInstanceRequest requestResponse : requestResponses) {
        System.out.println("Created Spot Request: " + requestResponse.getSpotInstanceRequestId());
        spotInstanceRequestIds.add(requestResponse.getSpotInstanceRequestId());
    }

}

From source file:de.unibi.cebitec.bibigrid.meta.aws.CreateClusterAWS.java

@Override
public CreateClusterAWS configureClusterMasterInstance() {
    // done for master. More volume description later when master is running

    ////////////////////////////////////////////////////////////////////////
    /////////////// preparing blockdevicemappings for master////////////////
    Map<String, String> masterSnapshotToMountPointMap = this.config.getMasterMounts();
    int ephemerals = config.getMasterInstanceType().getSpec().ephemerals;
    DeviceMapper masterDeviceMapper = new DeviceMapper(config.getMode(), masterSnapshotToMountPointMap,
            ephemerals);//from   www . j av  a 2s.c  o m
    masterDeviceMappings = new ArrayList<>();
    // create Volumes first
    if (!this.config.getMasterMounts().isEmpty()) {
        log.info(V, "Defining master volumes");
        masterDeviceMappings = createBlockDeviceMappings(masterDeviceMapper);
    }

    List<BlockDeviceMapping> ephemeralList = new ArrayList<>();
    for (int i = 0; i < this.config.getMasterInstanceType().getSpec().ephemerals; ++i) {
        BlockDeviceMapping temp = new BlockDeviceMapping();
        String virtualName = "ephemeral" + i;
        String deviceName = "/dev/sd" + ephemeral(i);
        temp.setVirtualName(virtualName);
        temp.setDeviceName(deviceName);
        ephemeralList.add(temp);
    }

    masterDeviceMappings.addAll(ephemeralList);

    base64MasterUserData = UserDataCreator.masterUserData(masterDeviceMapper, this.config,
            environment.getKeypair());

    log.info(V, "Master UserData:\n {}", new String(Base64.decodeBase64(base64MasterUserData)));
    //////////////////////////////////////////////////////////////////////////
    /////// create Placementgroup ////////////////////

    if (this.config.getMasterInstanceType().getSpec().clusterInstance) {
        if (config.isUseSpotInstances()) {
            spotInstancePlacement = new SpotPlacement(config.getAvailabilityZone());
            spotInstancePlacement.setGroupName(environment.getPlacementGroup());
        } else {
            instancePlacement = new Placement(this.config.getAvailabilityZone());
            instancePlacement.setGroupName(environment.getPlacementGroup());
        }
    }

    //////////////////////////////////////////////////////////////////////////
    /////// create NetworkInterfaceSpecification for MASTER instance with FIXED internal IP and public ip
    masterNetworkInterfaces = new ArrayList<>();

    inis = new InstanceNetworkInterfaceSpecification();
    inis.withPrivateIpAddress(environment.getMASTERIP()).withGroups(environment.getSecReqResult().getGroupId())
            .withAssociatePublicIpAddress(true).withSubnetId(environment.getSubnet().getSubnetId())
            .withDeviceIndex(0);

    masterNetworkInterfaces.add(inis); // add eth0

    slaveNetworkInterfaces = new ArrayList<>();
    inis = new InstanceNetworkInterfaceSpecification();
    inis.withGroups(environment.getSecReqResult().getGroupId())
            .withSubnetId(environment.getSubnet().getSubnetId())
            .withAssociatePublicIpAddress(config.isPublicSlaveIps()).withDeviceIndex(0);

    slaveNetworkInterfaces.add(inis);

    return this;
}

From source file:de.unibi.cebitec.bibigrid.meta.aws.CreateClusterAWS.java

@Override
public CreateClusterAWS configureClusterSlaveInstance() {
    //now defining Slave Volumes
    Map<String, String> snapShotToSlaveMounts = this.config.getSlaveMounts();
    int ephemerals = config.getSlaveInstanceType().getSpec().ephemerals;
    slaveDeviceMapper = new DeviceMapper(config.getMode(), snapShotToSlaveMounts, ephemerals);
    slaveBlockDeviceMappings = new ArrayList<>();
    // configure volumes first ...
    if (!snapShotToSlaveMounts.isEmpty()) {
        log.info(V, "configure slave volumes");
        slaveBlockDeviceMappings = createBlockDeviceMappings(slaveDeviceMapper);
    }/*from w ww.  ja v a  2 s  .co m*/
    // configure ephemeral devices
    List<BlockDeviceMapping> ephemeralList = new ArrayList<>();
    if (ephemerals > 0) {
        for (int i = 0; i < ephemerals; ++i) {
            BlockDeviceMapping temp = new BlockDeviceMapping();
            String virtualName = "ephemeral" + i;
            String deviceName = "/dev/sd" + ephemeral(i);
            temp.setVirtualName(virtualName);
            temp.setDeviceName(deviceName);
            ephemeralList.add(temp);
        }
    }

    slaveBlockDeviceMappings.addAll(ephemeralList);

    return this;
}

From source file:de.unibi.cebitec.bibigrid.meta.aws.CreateClusterAWS.java

private List<BlockDeviceMapping> createBlockDeviceMappings(DeviceMapper deviceMapper) {

    List<BlockDeviceMapping> mappings = new ArrayList<>();

    Map<String, String> snapshotToMountPointMap = deviceMapper.getSnapshotIdToMountPoint();
    for (Map.Entry<String, String> snapshotIdMountPoint : snapshotToMountPointMap.entrySet()) {
        try {//ww  w.  j  a v  a  2  s.com

            BlockDeviceMapping blockDeviceMapping = new BlockDeviceMapping();
            blockDeviceMapping.setEbs(new EbsBlockDevice()
                    .withSnapshotId(DeviceMapper.stripSnapshotId(snapshotIdMountPoint.getKey())));
            blockDeviceMapping
                    .setDeviceName(deviceMapper.getDeviceNameForSnapshotId(snapshotIdMountPoint.getKey()));

            mappings.add(blockDeviceMapping);

        } catch (AmazonServiceException ex) {
            log.debug("{}", ex.getMessage());

        }
    }
    return mappings;
}

From source file:eu.stratosphere.nephele.instance.ec2.EC2CloudManager.java

License:Apache License

/**
 * Requests (allocates) instances (VMs) from Amazon EC2.
 * //w ww .j  a va2  s  . c o m
 * @param awsAccessId
 *        the access ID into AWS
 * @param awsSecretKey
 *        the secret key used to generate signatures for authentication
 * @param instancesToBeRequested
 *        Map containing desired instances types and count
 * @param sshKeyPair
 *        Optional parameter to insert an EC2 SSH key/value pair
 * @return
 *         List containing the instance IDs of the allocated instances.
 */
private LinkedList<String> allocateCloudInstance(final Configuration conf, final InstanceType type,
        final int mincount, final int maxcount) {

    final String awsAccessId = conf.getString(AWS_ACCESS_ID_KEY, null);
    final String awsSecretKey = conf.getString(AWS_SECRET_KEY_KEY, null);

    final String imageID = conf.getString(AWS_AMI_KEY, null);
    LOG.info("Read Amazon Machine Image from job configuration: " + imageID);

    final String jobManagerIPAddress = GlobalConfiguration.getString("jobmanager.rpc.address", null);
    if (jobManagerIPAddress == null) {
        LOG.error("JobManager IP address is not set (jobmanager.rpc.address)");
        return null;
    }
    final String sshKeyPair = conf.getString("job.ec2.sshkeypair", null);

    final AmazonEC2Client ec2client = EC2ClientFactory.getEC2Client(awsAccessId, awsSecretKey);
    final LinkedList<String> instanceIDs = new LinkedList<String>();

    // Iterate over instance types..

    final RunInstancesRequest request = new RunInstancesRequest(imageID, mincount, maxcount);
    request.setInstanceType(type.getIdentifier());

    // Set availability zone if configured
    String av = null;
    if (this.availabilityZone != null) {
        av = this.availabilityZone;
    }
    final String jobAV = conf.getString("job.ec2.availabilityzone", null);
    if (jobAV != null) {
        LOG.info("Found " + jobAV + " as job-specific preference for availability zone");
        av = jobAV;
    }

    if (av != null) {
        request.setPlacement(new Placement(av));
    }

    // TODO: Make this configurable!
    final BlockDeviceMapping bdm = new BlockDeviceMapping();
    bdm.setVirtualName("ephemeral0");
    bdm.setDeviceName("/dev/sdb1");

    if (sshKeyPair != null) {
        request.setKeyName(sshKeyPair);
    }

    final LinkedList<BlockDeviceMapping> bdmlist = new LinkedList<BlockDeviceMapping>();
    bdmlist.add(bdm);
    request.setBlockDeviceMappings(bdmlist);

    // Setting User-Data parameters
    request.setUserData(EC2Utilities.createTaskManagerUserData(jobManagerIPAddress));

    // Request instances!
    try {
        final RunInstancesResult result = ec2client.runInstances(request);

        for (Instance i : result.getReservation().getInstances()) {
            instanceIDs.add(i.getInstanceId());
        }
    } catch (AmazonClientException e) {
        // Only log the error here
        LOG.error(StringUtils.stringifyException(e));
    }

    return instanceIDs;
}

From source file:org.cloudifysource.esc.driver.provisioning.privateEc2.PrivateEC2CloudifyDriver.java

License:Open Source License

private BlockDeviceMapping createBlockDeviceMapping(final String device, final AWSEC2Volume volumeConfig)
        throws CloudProvisioningException {
    final VolumeProperties volumeProperties = volumeConfig.getProperties();
    final Integer iops = volumeProperties.getIops() == null ? null : volumeProperties.getIops();
    final Integer size = volumeProperties.getSize();
    final String snapshotId = volumeProperties.getSnapshotId() == null ? null
            : volumeProperties.getSnapshotId().getValue();
    final String volumeType = volumeProperties.getVolumeType() == null ? null
            : volumeProperties.getVolumeType().getValue();

    final EbsBlockDevice ebs = new EbsBlockDevice();
    ebs.setIops(iops);//  w  w w  . j  a v a2  s .co m
    ebs.setSnapshotId(snapshotId);
    ebs.setVolumeSize(size);
    ebs.setVolumeType(volumeType);
    ebs.setDeleteOnTermination(true);

    final BlockDeviceMapping mapping = new BlockDeviceMapping();
    mapping.setDeviceName(device);
    mapping.setEbs(ebs);
    return mapping;
}

From source file:org.xmlsh.aws.util.AWSEC2Command.java

License:BSD License

protected BlockDeviceMapping parseBlockDeviceMapping(String string) throws InvalidArgumentException {
    BlockDeviceMapping map = new BlockDeviceMapping();
    StringPair pair = new StringPair(string, '=');

    String device = pair.getLeft();
    // if( device.startsWith("/dev/"))
    // device = device.substring(5);

    if (!pair.hasRight()) {
        map.setNoDevice(device);/*from  ww w .  j a  va 2s .  c  om*/
        return map;
    }

    String r = pair.getRight();
    if (r.equals("none")) {
        map.setNoDevice(device);
        return map;
    }

    map.setDeviceName(device);

    // Ephemeral = virtual ?
    if (!r.contains(":")) {
        map.setVirtualName(r);
        return map;
    }

    // Parse out the EBS stuff
    // [snapshot-id]:[volume-size]:[delete-on-termination]:[volume-type[:iops]]:[encrypted]

    String aebs[] = r.split(":");

    EbsBlockDevice ebs = new EbsBlockDevice();

    // [snapshot-id]:
    if (aebs.length >= 1) {
        String snapshotId = aebs[0];
        if (!Util.isBlank(snapshotId))
            ebs.setSnapshotId(snapshotId);

    }
    // :[volume-size]:
    if (aebs.length >= 2) {
        if (!Util.isBlank(aebs[1]))
            ebs.setVolumeSize(new Integer(aebs[1]));

    }

    // [delete-on-termination]:
    if (aebs.length >= 3) {
        if (!Util.isBlank(aebs[2]))
            ebs.setDeleteOnTermination(Boolean.valueOf(Util.parseBoolean(aebs[2])));

    }
    if (aebs.length >= 4) {
        // [volume-type[:iops]]:[encrypted]
        int i = 3;
        if (!Util.isBlank(aebs[i])) {
            ebs.setVolumeType(aebs[i]);
            if (aebs[i].equals(VolumeType.Io1.toString())) {
                i++;
                if (aebs.length <= i || Util.isBlank(aebs[i]))
                    throw new InvalidArgumentException(
                            "EBS block mapping with VolumeType :io1 MUST have PIOPS");
                ebs.setIops(Integer.valueOf(aebs[i]));
            }
            i++;
            if (aebs.length > i)
                ebs.setEncrypted(Util.parseBoolean(aebs[i]));
        }
    }

    map.setEbs(ebs);
    return map;

}