Example usage for com.amazonaws.services.ec2.model InstanceType fromValue

List of usage examples for com.amazonaws.services.ec2.model InstanceType fromValue

Introduction

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

Prototype

public static InstanceType fromValue(String value) 

Source Link

Document

Use this in place of valueOf.

Usage

From source file:com.appdynamics.connectors.AWSConnector.java

License:Apache License

private InstanceType getInstanceType(IProperty[] macProps) {
    String instanceTypeString = Utils.getInstanceType(macProps, controllerServices);

    InstanceType instanceType = InstanceType.M1Small;
    try {//from w  ww.j  a  va 2s.co  m
        instanceType = InstanceType.fromValue(instanceTypeString);
    } catch (IllegalArgumentException e) { //Should never occur
        logger.log(Level.INFO, "Invalid instance type. Using m1.small", e);
    }
    return instanceType;
}

From source file:com.kenlin.awsec2offering.App.java

License:Open Source License

public static InstanceType parseInstanceType(String value) {
    if (value == null) {
        return null;
    } else {/*from   www  . jav a2 s .c o  m*/
        return InstanceType.fromValue(value);
    }
}

From source file:com.norbl.cbp.ppe.Ec2InstanceType.java

License:Open Source License

/** NOTE/WARNING: there is a bug in the aws implementation of
 *  {@link InstanceType#valueOf(java.lang.String) }.
 *  It throws an exception on t1.micro even if it obtained from 
 *  {@link InstanceType#values() }.toString(). They've added a kluge method
 *  {@link InstanceType#fromValue(java.lang.String) } that solves the problem.
 *  That method is used in this function.  All instance type translation should
 *  be done with this method only./*from   w  w  w. j a  va  2 s .c o  m*/
 * 
 * @param instanceTypeName
 * @return
 * @throws IllegalArgumentException 
 */
public static InstanceType getInstanceType(String instanceTypeName) throws IllegalArgumentException {
    return (InstanceType.fromValue(instanceTypeName));
}

From source file:com.yosanai.java.aws.console.panel.LaunchDialog.java

License:Open Source License

private void cboInstanceActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_cboInstanceActionPerformed
    Object obj = cboInstance.getSelectedItem();
    if (null != obj) {
        txtDesc.setText(Messages.getString("InstanceType." + InstanceType.fromValue(obj.toString()).name()));
    }//from   w ww  . ja  va 2 s.c  om
}

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

@Override
public boolean launchClusterInstances() {
    log.info("Requesting master instance ...");

    if (config.isUseSpotInstances()) {
        RequestSpotInstancesRequest masterReq = new RequestSpotInstancesRequest();
        masterReq.withType(SpotInstanceType.OneTime).withInstanceCount(1).withLaunchGroup("lg_" + clusterId)
                .withSpotPrice(Double.toString(config.getBidPriceMaster()));

        LaunchSpecification masterLaunchSpecification = new LaunchSpecification();
        masterLaunchSpecification//ww w  . j  av  a  2 s.c o m
                .withInstanceType(InstanceType.fromValue(this.config.getMasterInstanceType().getValue()))
                .withPlacement(spotInstancePlacement).withKeyName(this.config.getKeypair())
                .withImageId(this.config.getMasterImage()).withUserData(base64MasterUserData)
                .withBlockDeviceMappings(masterDeviceMappings).withNetworkInterfaces(masterNetworkInterfaces);

        masterReq.setLaunchSpecification(masterLaunchSpecification);

        RequestSpotInstancesResult masterReqResult = ec2.requestSpotInstances(masterReq);

        List<SpotInstanceRequest> masterReqResponses = masterReqResult.getSpotInstanceRequests();
        // collect all spotInstanceRequestIds ...
        List<String> spotInstanceRequestIds = new ArrayList<>();

        for (SpotInstanceRequest requestResponse : masterReqResponses) {

            spotInstanceRequestIds.add(requestResponse.getSpotInstanceRequestId());

        }
        // Tag spotrequest
        CreateTagsRequest ctr = new CreateTagsRequest();
        ctr.withResources(spotInstanceRequestIds);
        ctr.withTags(bibigridid, username, new Tag().withKey("Name").withValue(PREFIX + "master-" + clusterId));
        ec2.createTags(ctr);
        // Wait for spot request finished  
        log.info("Waiting for master instance (spot request) to finish booting ...");
        masterInstance = waitForInstances(waitForSpotInstances(spotInstanceRequestIds)).get(0);
    } else {

        RunInstancesRequest masterReq = new RunInstancesRequest();
        masterReq.withInstanceType(InstanceType.fromValue(this.config.getMasterInstanceType().getValue()))
                .withMinCount(1).withMaxCount(1).withPlacement(instancePlacement)
                .withKeyName(this.config.getKeypair()).withImageId(this.config.getMasterImage())
                .withUserData(base64MasterUserData).withBlockDeviceMappings(masterDeviceMappings)
                .withNetworkInterfaces(masterNetworkInterfaces);

        // mounting ephemerals
        RunInstancesResult masterReqResult = ec2.runInstances(masterReq);
        String masterReservationId = masterReqResult.getReservation().getReservationId();
        masterInstance = masterReqResult.getReservation().getInstances().get(0);
        log.info("Waiting for master instance to finish booting ...");

        /////////////////////////////////////////////
        //// Waiting for master instance to run ////
        masterInstance = waitForInstances(Arrays.asList(new String[] { masterInstance.getInstanceId() }))
                .get(0);

    }
    log.info(I, "Master instance is now running!");

    ModifyInstanceAttributeRequest ia_req = new ModifyInstanceAttributeRequest();
    ia_req.setInstanceId(masterInstance.getInstanceId());
    ia_req.setSourceDestCheck(Boolean.FALSE);
    ec2.modifyInstanceAttribute(ia_req);

    ////////////////////////////////////
    //// Tagging Master with a name ////
    CreateTagsRequest masterNameTagRequest = new CreateTagsRequest();
    masterNameTagRequest.withResources(masterInstance.getInstanceId()).withTags(bibigridid, username,
            new Tag().withKey("Name").withValue(PREFIX + "master-" + clusterId));

    ec2.createTags(masterNameTagRequest);

    /*
     * Waiting for Status Checks to finish
     *
     */
    log.info("Waiting for Status Checks on master ...");
    do {
        DescribeInstanceStatusRequest request = new DescribeInstanceStatusRequest();
        request.setInstanceIds((Arrays.asList(new String[] { masterInstance.getInstanceId() })));

        DescribeInstanceStatusResult response = ec2.describeInstanceStatus(request);

        InstanceStatus status = response.getInstanceStatuses().get(0);
        String instanceStatus = status.getInstanceStatus().getStatus();
        String systemStatus = status.getSystemStatus().getStatus();
        log.debug("Status of master instance: " + instanceStatus + "," + systemStatus);
        if (instanceStatus.equalsIgnoreCase("ok") && systemStatus.equalsIgnoreCase("ok")) {
            break;
        } else {
            log.info(V, "...");
            sleep(10);
        }
    } while (true);
    log.info(I, "Status checks successful.");
    ////////////////////////////////////////////////////////////////////////
    ///// run slave instances and supply userdata //////////////////////////

    if (config.getSlaveInstanceCount() > 0) {

        String base64SlaveUserData = UserDataCreator.forSlave(masterInstance.getPrivateIpAddress(),
                masterInstance.getPrivateDnsName(), slaveDeviceMapper, this.config, environment.getKeypair());

        log.info(V, "Slave Userdata:\n{}", new String(Base64.decodeBase64(base64SlaveUserData)));

        if (config.isUseSpotInstances()) {
            RequestSpotInstancesRequest slaveReq = new RequestSpotInstancesRequest();
            slaveReq.withType(SpotInstanceType.OneTime).withInstanceCount(config.getSlaveInstanceCount())
                    .withLaunchGroup("lg_" + clusterId).withSpotPrice(Double.toString(config.getBidPrice()));

            LaunchSpecification slaveLaunchSpecification = new LaunchSpecification();
            slaveLaunchSpecification
                    .withInstanceType(InstanceType.fromValue(this.config.getSlaveInstanceType().getValue()))
                    .withPlacement(spotInstancePlacement).withKeyName(this.config.getKeypair())
                    .withImageId(this.config.getSlaveImage()).withUserData(base64SlaveUserData)
                    .withBlockDeviceMappings(slaveBlockDeviceMappings)
                    .withNetworkInterfaces(slaveNetworkInterfaces);

            slaveReq.setLaunchSpecification(slaveLaunchSpecification);

            RequestSpotInstancesResult slaveReqResult = ec2.requestSpotInstances(slaveReq);

            List<SpotInstanceRequest> slaveReqResponses = slaveReqResult.getSpotInstanceRequests();
            // collect all spotInstanceRequestIds ...
            List<String> spotInstanceRequestIds = new ArrayList<>();

            for (SpotInstanceRequest requestResponse : slaveReqResponses) {

                spotInstanceRequestIds.add(requestResponse.getSpotInstanceRequestId());

            }
            // wait for a second
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {

            }

            log.info(V, "tag spot request instances");

            // tag spot requests (slave)
            CreateTagsRequest ctr = new CreateTagsRequest();
            ctr.withResources(spotInstanceRequestIds);
            ctr.withTags(bibigridid, username,
                    new Tag().withKey("Name").withValue(PREFIX + "slave-" + clusterId));
            /* Setting tags for spot requests can cause an amazon service 
             exception, if the spot request returns an id, but the id 
             isn't registered in spot request registy yet. */
            int counter = 0;
            boolean finished = false;
            while (!finished) {
                try {
                    ec2.createTags(ctr);
                    finished = true;
                } catch (AmazonServiceException ase) {
                    if (counter < 5) {
                        log.warn("{} ... try again in 10 seconds.", ase.getMessage());
                        try {
                            Thread.sleep(10000);
                        } catch (InterruptedException e) {
                        }
                        counter++;
                    } else {
                        throw ase;
                    }
                }
            }
            log.info("Waiting for slave instance(s) (spot request) to finish booting ...");
            // wait for spot request (slave) finished
            slaveInstances = waitForInstances(waitForSpotInstances(spotInstanceRequestIds));

        } else {

            RunInstancesRequest slaveReq = new RunInstancesRequest();
            slaveReq.withInstanceType(InstanceType.fromValue(this.config.getSlaveInstanceType().getValue()))
                    .withMinCount(this.config.getSlaveInstanceCount())
                    .withMaxCount(this.config.getSlaveInstanceCount()).withPlacement(instancePlacement)
                    .withKeyName(this.config.getKeypair()).withImageId(this.config.getSlaveImage())
                    .withUserData(base64SlaveUserData).withBlockDeviceMappings(slaveBlockDeviceMappings)
                    .withNetworkInterfaces(slaveNetworkInterfaces);

            RunInstancesResult slaveReqResult = ec2.runInstances(slaveReq);
            String slaveReservationId = slaveReqResult.getReservation().getReservationId();
            // create a list of all slave instances
            List<String> slaveInstanceListIds = new ArrayList<>();
            for (Instance i : slaveReqResult.getReservation().getInstances()) {
                slaveInstanceListIds.add(i.getInstanceId());
            }

            log.info("Waiting for slave instance(s) to finish booting ...");
            slaveInstances = waitForInstances(slaveInstanceListIds);

        }

        /////////////////////////////////////////////
        //// Waiting for master instance to run ////
        log.info(I, "Slave instance(s) is now running!");

        ////////////////////////////////////
        //// Tagging all slaves  with a name
        for (Instance si : slaveInstances) {
            CreateTagsRequest slaveNameTagRequest = new CreateTagsRequest();
            slaveNameTagRequest.withResources(si.getInstanceId()).withTags(bibigridid, username,
                    new Tag().withKey("Name").withValue(PREFIX + "slave-" + clusterId));
            ec2.createTags(slaveNameTagRequest);
        }
    } else {
        log.info("No Slave instance(s) requested !");

    }

    //////////////////////////////////
    ////// post configure master
    configureMaster();

    ////////////////////////////////////
    //// Human friendly output
    StringBuilder sb = new StringBuilder();
    sb.append("\n You might want to set the following environment variable:\n\n");
    sb.append("export BIBIGRID_MASTER=").append(masterInstance.getPublicIpAddress()).append("\n\n");
    sb.append("You can then log on the master node with:\n\n").append("ssh -i ")
            .append(config.getIdentityFile()).append(" ubuntu@$BIBIGRID_MASTER\n\n");
    sb.append("The cluster id of your started cluster is : ").append(clusterId).append("\n\n");
    sb.append("The can easily terminate the cluster at any time with :\n").append("./bibigrid -t ")
            .append(clusterId).append(" ");
    if (getConfig().isAlternativeConfigFile()) {
        sb.append("-o ").append(config.getAlternativeConfigPath()).append(" ");
    }

    sb.append("\n");

    log.info(sb.toString());

    ////////////////////////////////////
    //// Grid Properties file
    if (getConfig().getGridPropertiesFile() != null) {
        Properties gp = new Properties();
        gp.setProperty("BIBIGRID_MASTER", masterInstance.getPublicIpAddress());
        gp.setProperty("IdentityFile", getConfig().getIdentityFile().toString());
        gp.setProperty("clusterId", clusterId);
        if (getConfig().isAlternativeConfigFile()) {
            gp.setProperty("AlternativeConfigFile", config.getAlternativeConfigPath());
        }
        try {
            gp.store(new FileOutputStream(getConfig().getGridPropertiesFile()), "Autogenerated by BiBiGrid");
        } catch (IOException e) {
            log.error(I, "Exception while creating grid properties file : " + e.getMessage());
        }
    }

    return true;
}

From source file:eu.optimis.monitoring.amazoncollector.MeasurementsHelper.java

License:Apache License

public List<Measurement> getMeasurements() {
    AmazonEC2 ec2 = getAmazonEC2Client();
    List<Measurement> measurements = new LinkedList<Measurement>();

    List<Filter> filters = new LinkedList<Filter>();
    List<String> tags = new LinkedList<String>();
    tags.add(SERVICE_ID_TAG);/*from w  w  w  . j a va  2s  .c  o m*/
    Filter f = new Filter("tag-key", tags);
    filters.add(f);
    DescribeInstancesRequest req = new DescribeInstancesRequest();
    req.setFilters(filters);

    DescribeInstancesResult res;
    try {
        res = ec2.describeInstances(req);
    } catch (AmazonServiceException se) {
        printServiceException(se);
        throw new RuntimeException("Exception while trying to get information about running instances");
    }
    List<Instance> instances = new ArrayList<Instance>();
    for (Reservation r : res.getReservations()) {
        instances.addAll(r.getInstances());
    }

    for (Instance i : instances) {
        String instance_id = i.getInstanceId();
        InstanceType type = InstanceType.fromValue(i.getInstanceType());
        String ami_id = i.getImageId();
        String architecture = i.getArchitecture();
        String state = i.getState().getName();

        List<String> volume_ids = new LinkedList<String>();
        for (InstanceBlockDeviceMapping mapping : i.getBlockDeviceMappings()) {
            volume_ids.add(mapping.getEbs().getVolumeId());
        }

        String service_id = "";
        List<Tag> itags = i.getTags();
        for (Tag t : itags) {
            if (t.getKey().equals(SERVICE_ID_TAG)) {
                service_id = t.getValue();
                break;
            }
        }

        try {
            measurements.add(
                    new Measurement("machine_type", architecture, "", new Date(), instance_id, service_id));
            measurements.add(new Measurement("vm_status", state, "", new Date(), instance_id, service_id));

            Measurement m_mem = getTotalMemory(type, instance_id, service_id);
            Measurement m_cpu = getCPUSpeed(type, instance_id, service_id);
            Measurement m_cores = getNumVCores(type, instance_id, service_id);
            Measurement m_os = getOSRelease(ami_id, instance_id, service_id);
            Measurement m_disk = getTotalDiskSize(volume_ids, instance_id, service_id);
            Measurement m_memused = getCWMeasurement("MemoryUsed", "mem_used", true, instance_id, service_id);
            Measurement m_cpuutil = getCWMeasurement("CPUUtilization", "cpu_used", false, instance_id,
                    service_id);
            Measurement m_nout = getCWMeasurement("NetworkOut", "network_out", false, instance_id, service_id);
            Measurement m_nin = getCWMeasurement("NetworkIn", "network_in", false, instance_id, service_id);

            if (m_mem != null)
                measurements.add(m_mem);
            if (m_cpu != null)
                measurements.add(m_cpu);
            if (m_cores != null)
                measurements.add(m_cores);
            if (m_os != null)
                measurements.add(m_os);
            if (m_disk != null)
                measurements.add(m_disk);
            if (m_memused != null)
                measurements.add(m_memused);
            if (m_cpuutil != null)
                measurements.add(m_cpuutil);
            if (m_nout != null)
                measurements.add(m_nout);
            if (m_nin != null)
                measurements.add(m_nin);

        } catch (AmazonServiceException se) {
            printServiceException(se);
            throw new RuntimeException("Exception while trying to retrieve some metrics");
        }
    }

    return measurements;
}

From source file:jp.primecloud.auto.service.impl.InstanceServiceImpl.java

License:Open Source License

private void makeAwsData(Farm farm, Long instanceNo, String instanceType, PlatformAws platformAws) {

    // ?// www  . j  a  va  2 s.c o  m
    try {
        InstanceType.fromValue(instanceType);
    } catch (IllegalArgumentException e) {
        throw new AutoApplicationException("ECOMMON-000001", "instanceType");
    }

    // AWS??
    AwsInstance awsInstance = new AwsInstance();
    awsInstance.setInstanceNo(instanceNo);
    awsInstance.setInstanceType(instanceType);

    //KeyName
    AwsCertificate awsCertificate = awsCertificateDao.read(farm.getUserNo(), platformAws.getPlatformNo());
    //??
    List<KeyPairDto> keyPairInfos = iaasDescribeService.getKeyPairs(farm.getUserNo(),
            platformAws.getPlatformNo());
    String keyName = null;
    // AWS?????
    for (KeyPairDto keyPairDto : keyPairInfos) {
        if (StringUtils.equals(awsCertificate.getDefKeypair(), keyPairDto.getKeyName())) {
            keyName = keyPairDto.getKeyName();
            break;
        }
    }
    if (keyName == null && keyPairInfos.size() > 0) {
        //??????1
        keyName = keyPairInfos.get(0).getKeyName();
    }
    awsInstance.setKeyName(keyName);

    String subnetId = null;
    if (platformAws.getEuca() == false && platformAws.getVpc()) {
        // VPC??
        // SubnetId & AvailabilityZone
        List<SubnetDto> subnets = iaasDescribeService.getSubnets(farm.getUserNo(), platformAws.getPlatformNo(),
                platformAws.getVpcId());
        SubnetDto subnet = null;
        for (SubnetDto subnetDto : subnets) {
            //?
            if (StringUtils.equals(awsCertificate.getDefSubnet(), subnetDto.getSubnetId())
                    && StringUtils.equals(platformAws.getAvailabilityZone(), subnetDto.getZoneid())) {
                //?????
                subnet = subnetDto;
                break;
            }
        }
        if (subnet != null) {
            subnetId = subnet.getSubnetId();
            awsInstance.setSubnetId(subnetId);
            awsInstance.setAvailabilityZone(subnet.getZoneid());
        }
    } else {
        // VPC????
        // AvailabilityZone
        String zoneName = platformAws.getAvailabilityZone();
        if (StringUtils.isEmpty(zoneName) && platformAws.getEuca()) {
            // ?????????Eucalyptus????API?????
            List<ZoneDto> availabilityZones = iaasDescribeService.getAvailabilityZones(farm.getUserNo(),
                    platformAws.getPlatformNo());

            zoneName = availabilityZones.get(0).getZoneName();
        }
        awsInstance.setAvailabilityZone(zoneName);
    }

    // SecurityGroup
    String groupName = null;
    List<SecurityGroupDto> securityGroups = null;
    if (platformAws.getEuca() == false && platformAws.getVpc()) {
        // VPC??
        securityGroups = iaasDescribeService.getSecurityGroups(farm.getUserNo(), platformAws.getPlatformNo(),
                platformAws.getVpcId());
    } else {
        // VPC????
        securityGroups = iaasDescribeService.getSecurityGroups(farm.getUserNo(), platformAws.getPlatformNo(),
                null);
    }

    groupName = setSecurityGroup(securityGroups, "aws.defaultSecurityGroup");

    awsInstance.setSecurityGroups(groupName);

    awsInstanceDao.create(awsInstance);
}

From source file:jp.primecloud.auto.service.impl.InstanceServiceImpl.java

License:Open Source License

/**
 * {@inheritDoc}//from  w  w  w.  j a va2  s.  c  om
 */
@Override
public void updateAwsInstance(Long instanceNo, String instanceName, String comment, String keyName,
        String instanceType, String securityGroupName, String availabilityZoneName, Long addressNo,
        String subnetId, String privateIpAddress) {
    // ?
    updateInstance(instanceNo, instanceName, comment);

    // ?
    if (instanceNo == null) {
        throw new AutoApplicationException("ECOMMON-000003", "instanceNo");
    }
    if (keyName == null || keyName.length() == 0) {
        throw new AutoApplicationException("ECOMMON-000003", "keyName");
    }
    try {
        InstanceType.fromValue(instanceType);
    } catch (IllegalArgumentException e) {
        throw new AutoApplicationException("ECOMMON-000001", "instanceType");
    }

    // ??
    Instance instance = instanceDao.read(instanceNo);
    if (instance == null) {
        throw new AutoApplicationException("ESERVICE-000403", instanceNo);
    }

    // ??
    Platform platform = platformDao.read(instance.getPlatformNo());
    if (PCCConstant.PLATFORM_TYPE_AWS.equals(platform.getPlatformType()) == false) {
        throw new AutoApplicationException("ESERVICE-000404", instance.getInstanceName());
    }

    //?
    Farm farm = farmDao.read(instance.getFarmNo());

    // ??????
    AwsInstance awsInstance = awsInstanceDao.read(instanceNo);
    if (InstanceStatus.fromStatus(instance.getStatus()) != InstanceStatus.STOPPED) {
        // ??????????????????
        if (!StringUtils.equals(awsInstance.getKeyName(), keyName)) {
            throw new AutoApplicationException("ESERVICE-000407", instance.getInstanceName());
        }
        if (!StringUtils.equals(awsInstance.getInstanceType(), instanceType)) {
            throw new AutoApplicationException("ESERVICE-000407", instance.getInstanceName());
        }
        if (StringUtils.isEmpty(awsInstance.getSecurityGroups()) ? StringUtils.isNotEmpty(securityGroupName)
                : !StringUtils.equals(awsInstance.getSecurityGroups(), securityGroupName)) {
            throw new AutoApplicationException("ESERVICE-000407", instance.getInstanceName());
        }
        if (StringUtils.isEmpty(awsInstance.getAvailabilityZone())
                ? StringUtils.isNotEmpty(availabilityZoneName)
                : !StringUtils.equals(awsInstance.getAvailabilityZone(), availabilityZoneName)) {
            throw new AutoApplicationException("ESERVICE-000407", instance.getInstanceName());
        }
        if (StringUtils.isEmpty(awsInstance.getSubnetId()) ? StringUtils.isNotEmpty(subnetId)
                : !StringUtils.equals(awsInstance.getSubnetId(), subnetId)) {
            throw new AutoApplicationException("ESERVICE-000407", instance.getInstanceName());
        }
        if (StringUtils.isEmpty(awsInstance.getPrivateIpAddress()) ? StringUtils.isNotEmpty(privateIpAddress)
                : !StringUtils.equals(awsInstance.getPrivateIpAddress(), privateIpAddress)) {
            throw new AutoApplicationException("ESERVICE-000407", instance.getInstanceName());
        }
    }

    // ??
    if (StringUtils.isEmpty(awsInstance.getSubnetId()) && StringUtils.isEmpty(securityGroupName)) {
        throw new AutoApplicationException("ECOMMON-000003", "securityGroupName");
    }

    // ??
    PlatformAws platformAws = platformAwsDao.read(instance.getPlatformNo());
    if (platformAws.getEuca() == false && platformAws.getVpc()) {
        if (StringUtils.equals(awsInstance.getSubnetId(), subnetId) == false) {
            //VPC????????????
            if (awsVolumeDao.countByInstanceNo(instanceNo) > 0) {
                // EBS???()?????
                throw new AutoApplicationException("ESERVICE-000421");
            }
        }
    } else {
        if (StringUtils.isEmpty(awsInstance.getAvailabilityZone())
                ? StringUtils.isNotEmpty(availabilityZoneName)
                : !StringUtils.equals(awsInstance.getAvailabilityZone(), availabilityZoneName)) {
            if (awsVolumeDao.countByInstanceNo(instanceNo) > 0) {
                // EBS???????
                throw new AutoApplicationException("ESERVICE-000412");
            }
        }
    }

    //???
    if (StringUtils.isNotEmpty(subnetId) && StringUtils.isNotEmpty(privateIpAddress)) {
        //AWS_INSTANCE?subnet??
        List<Instance> instances = instanceDao.readByFarmNo(farm.getFarmNo());
        List<Long> instanceNos = new ArrayList<Long>();
        for (Instance tmpInstance : instances) {
            if (instanceNo.equals(tmpInstance.getInstanceNo()) == false) {
                instanceNos.add(tmpInstance.getInstanceNo());
            }
        }
        List<AwsInstance> awsInstances = awsInstanceDao.readInInstanceNos(instanceNos);
        for (AwsInstance tmpAwsInstance : awsInstances) {
            if (subnetId.equals(tmpAwsInstance.getSubnetId())
                    && privateIpAddress.equals(tmpAwsInstance.getPrivateIpAddress())) {
                //??subnetId???privateIpAddress??AWS_INSTANCE???
                throw new AutoApplicationException("ESERVICE-000420", privateIpAddress);
            }
        }
    }

    // AWS??
    AwsAddress awsAddress = null;
    if (addressNo != null) {
        // AWS??
        awsAddress = awsAddressDao.read(addressNo);
        if (awsAddress == null) {
            throw new AutoApplicationException("ESERVICE-000415", addressNo);
        }

        // ????????????
        if (awsAddress.getInstanceNo() != null && !instanceNo.equals(awsAddress.getInstanceNo())) {
            // ??????
            throw new AutoApplicationException("ESERVICE-000416", awsAddress.getPublicIp());
        }
    }

    // AWS?
    awsInstance.setKeyName(keyName);
    awsInstance.setInstanceType(instanceType);
    awsInstance.setSecurityGroups(securityGroupName);
    awsInstance.setAvailabilityZone(availabilityZoneName);
    awsInstance.setSubnetId(subnetId);
    awsInstance.setPrivateIpAddress(privateIpAddress);
    awsInstanceDao.update(awsInstance);

    // ?AWS????????
    List<AwsAddress> awsAddresses = awsAddressDao.readByInstanceNo(instanceNo);
    for (AwsAddress address : awsAddresses) {
        if (address.getAddressNo().equals(addressNo)) {
            continue;
        }
        address.setInstanceNo(null);
        awsAddressDao.update(address);
    }

    // AWS??
    if (addressNo != null && !instanceNo.equals(awsAddress.getInstanceNo())) {
        awsAddress.setInstanceNo(instanceNo);
        awsAddressDao.update(awsAddress);
    }

    // 
    eventLogger.log(EventLogLevel.INFO, farm.getFarmNo(), farm.getFarmName(), null, null, instanceNo,
            instanceName, "InstanceUpdate", instanceType, instance.getPlatformNo(), null);
}

From source file:net.firejack.aws.web.controller.AWSController.java

License:Apache License

@ResponseBody
@RequestMapping(value = "install", method = RequestMethod.POST)
public Status startInstance(@RequestBody Auth auth) {
    if (!auth.isValid())
        throw new AmazonServiceException("Access or Secret Key is empty");

    if (amazonEC2 != null) {
        amazonEC2.shutdown();/*from  w w w .  j  a v  a 2s.  co m*/
    }

    amazonEC2 = new AmazonEC2Client(new BasicAWSCredentials(auth.getAccessKey(), auth.getSecretKey()));
    amazonEC2.setRegion(RegionUtils.getRegion(instanceRegion));

    RunInstancesRequest runInstancesRequest = new RunInstancesRequest();
    runInstancesRequest.setInstanceType(InstanceType.fromValue(instanceType));
    runInstancesRequest.setImageId(instanceAmi);
    runInstancesRequest.setMinCount(1);
    runInstancesRequest.setMaxCount(1);

    KeyPair keyPair = createKeyPair();
    String privateKey = keyPair.getKeyMaterial();
    String fileName;
    try {
        fileName = saveKeyFile(keyPair.getKeyName(), privateKey);
    } catch (FileNotFoundException e) {
        throw new AmazonServiceException("Could not create the key file");
    } catch (UnsupportedEncodingException e) {
        throw new AmazonServiceException("Could not create the key file");
    }
    runInstancesRequest.setKeyName(keyPair.getKeyName());

    CreateSecurityGroupResult securityGroupResult = createSecurityGroupWithRules();
    Collection securityGroupIds = new ArrayList();
    securityGroupIds.add(securityGroupResult.getGroupId());
    runInstancesRequest.setSecurityGroupIds(securityGroupIds);

    amazonEC2.runInstances(runInstancesRequest);

    return new Status("Server has been started", fileName);
}