Example usage for com.amazonaws.services.ec2.model RunInstancesRequest setSecurityGroupIds

List of usage examples for com.amazonaws.services.ec2.model RunInstancesRequest setSecurityGroupIds

Introduction

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

Prototype


public void setSecurityGroupIds(java.util.Collection<String> securityGroupIds) 

Source Link

Document

The IDs of the security groups.

Usage

From source file:AWS.java

private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed
    // TODO add your handling code here:
    // Group handealing

    List<String> groupID = new ArrayList<String>();
    String Temp_Group = "sg-aa5efdcf";

    groupID.add(Temp_Group);//wait to out our instance into this group

    System.out.println("#5 Create an Instance");
    String imageId = "ami-08be1f7f";//  
    int minInstanceCount = 1; // create 1 instance
    int maxInstanceCount = 1;
    RunInstancesRequest rir = new RunInstancesRequest(imageId, minInstanceCount, maxInstanceCount);

    rir.setInstanceType("t2.micro");
    rir.setKeyName("14_LP1_KEY_D7001D_aledem-4");// give the instance the key we just created
    // rir.setSecurityGroups(groupName);// set the instance in the group we just created
    rir.setSecurityGroupIds(groupID);
    rir.setSubnetId("subnet-47ca2d1e");

    RunInstancesResult result = ec2client.runInstances(rir);

    /***********to make sure the instance's state is "running instead of "pending",**********/
    /***********we wait for a while                                                **********/
    System.out.println("waiting");
    try {//w w  w . jav  a2 s .com
        Thread.currentThread().sleep(60000);
    } catch (InterruptedException ex) {
        Logger.getLogger(AWS.class.getName()).log(Level.SEVERE, null, ex);
    }
    System.out.println("OK");

    List<Instance> resultInstance = result.getReservation().getInstances();

    String createdInstanceId = null;
    for (Instance ins : resultInstance) {

        createdInstanceId = ins.getInstanceId();
        String createdInstanceIp = ins.getPublicDnsName();

        System.out.println("New instance has been created: " + ins.getInstanceId());//print the instance ID

    }

    System.out.println("#6 Create a 'tag' for the new instance.");
    List<String> resources = new LinkedList<>();
    List<Tag> tags = new LinkedList<>();
    Tag nameTag = new Tag("Name", "FromCoordinator");

    resources.add(createdInstanceId);
    tags.add(nameTag);

    CreateTagsRequest ctr = new CreateTagsRequest(resources, tags);
    ec2client.createTags(ctr);

    fetchInstanceInfo(createdInstanceId);
}

From source file:com.github.vatbub.awsvpnlauncher.Main.java

License:Apache License

/**
 * Launches a new VPN server on AWS EC2 if everything is configured
 *
 * @see PropertyNotConfiguredException/* w  w w  . ja  va2s.  c o  m*/
 * @see #terminate()
 */
private static void launch() {
    File privateKey = new File(prefs.getPreference(Property.privateKeyFile));
    vpnPassword = prefs.getPreference(Property.openvpnPassword);

    if (!privateKey.exists() && !privateKey.isFile()) {
        throw new IllegalArgumentException("The file specified as " + Property.privateKeyFile.toString()
                + " does not exist or is not a file.");
    }

    FOKLogger.info(Main.class.getName(), "Preparing...");

    try {
        // Check if our security group exists already
        FOKLogger.info(Main.class.getName(), "Checking for the required security group...");
        DescribeSecurityGroupsRequest describeSecurityGroupsRequest = new DescribeSecurityGroupsRequest()
                .withGroupNames(securityGroupName);

        List<String> securityGroups = new ArrayList<>();
        boolean created = false; // will become true if the security group had to be created to avoid duplicate logs
        String securityGroupId;
        try {
            DescribeSecurityGroupsResult describeSecurityGroupsResult = client
                    .describeSecurityGroups(describeSecurityGroupsRequest);
            securityGroupId = describeSecurityGroupsResult.getSecurityGroups().get(0).getGroupId();
        } catch (AmazonEC2Exception e) {
            // Security group does not exist, create the security group
            created = true;
            FOKLogger.info(Main.class.getName(), "Creating the required security group...");
            CreateSecurityGroupRequest createSecurityGroupRequest = new CreateSecurityGroupRequest()
                    .withGroupName(securityGroupName).withDescription(
                            "This security group was automatically created to run a OpenVPN Access Server.");
            CreateSecurityGroupResult createSecurityGroupResult = client
                    .createSecurityGroup(createSecurityGroupRequest);

            securityGroupId = createSecurityGroupResult.getGroupId();

            IpRange ipRange = new IpRange().withCidrIp("0.0.0.0/0");
            IpPermission sshPermission1 = new IpPermission().withIpv4Ranges(ipRange).withIpProtocol("tcp")
                    .withFromPort(22).withToPort(22);
            IpPermission sshPermission2 = new IpPermission().withIpv4Ranges(ipRange).withIpProtocol("tcp")
                    .withFromPort(943).withToPort(943);
            IpPermission httpsPermission1 = new IpPermission().withIpv4Ranges(ipRange).withIpProtocol("tcp")
                    .withFromPort(443).withToPort(443);
            IpPermission httpsPermission2 = new IpPermission().withIpv4Ranges(ipRange).withIpProtocol("udp")
                    .withFromPort(1194).withToPort(1194);

            AuthorizeSecurityGroupIngressRequest authorizeSecurityGroupIngressRequest = new AuthorizeSecurityGroupIngressRequest()
                    .withGroupName(securityGroupName).withIpPermissions(sshPermission1)
                    .withIpPermissions(sshPermission2).withIpPermissions(httpsPermission1)
                    .withIpPermissions(httpsPermission2);

            // retry while the security group is not yet ready
            int retries = 0;
            long lastPollTime = System.currentTimeMillis();
            boolean requestIsFailing = true;

            do {
                // we're waiting

                if (System.currentTimeMillis() - lastPollTime >= Math.pow(2, retries) * 100) {
                    retries = retries + 1;
                    lastPollTime = System.currentTimeMillis();
                    try {
                        client.authorizeSecurityGroupIngress(authorizeSecurityGroupIngressRequest);
                        // no exception => we made it
                        requestIsFailing = false;
                    } catch (AmazonEC2Exception e2) {
                        FOKLogger.info(Main.class.getName(),
                                "Still waiting for the security group to be created, api error message is currently: "
                                        + e2.getMessage());
                        requestIsFailing = true;
                    }
                }
            } while (requestIsFailing);
            FOKLogger.info(Main.class.getName(), "The required security group has been successfully created!");
        }

        if (!created) {
            FOKLogger.info(Main.class.getName(), "The required security group already exists, we can continue");
        }
        securityGroups.add(securityGroupId);

        securityGroups.add(securityGroupId);

        FOKLogger.info(Main.class.getName(), "Creating the RunInstanceRequest...");
        RunInstancesRequest request = new RunInstancesRequest(getAmiId(awsRegion), 1, 1);
        request.setInstanceType(InstanceType.T2Micro);
        request.setKeyName(prefs.getPreference(Property.awsKeyPairName));
        request.setSecurityGroupIds(securityGroups);

        FOKLogger.info(Main.class.getName(), "Starting the EC2 instance...");
        RunInstancesResult result = client.runInstances(request);
        List<Instance> instances = result.getReservation().getInstances();

        // SSH config
        FOKLogger.info(Main.class.getName(), "Configuring SSH...");
        Properties sshConfig = new Properties();
        sshConfig.put("StrictHostKeyChecking", "no");
        JSch jsch = new JSch();
        jsch.addIdentity(privateKey.getAbsolutePath());
        int retries = 0;

        for (Instance instance : instances) {
            // write the instance id to a properties file to be able to terminate it later on again
            prefs.reload();
            if (prefs.getPreference("instanceIDs", "").equals("")) {
                prefs.setPreference("instanceIDs", instance.getInstanceId());
            } else {
                prefs.setPreference("instanceIDs",
                        prefs.getPreference("instanceIDs", "") + ";" + instance.getInstanceId());
            }

            // Connect to the instance using ssh
            FOKLogger.info(Main.class.getName(), "Waiting for the instance to boot...");

            long lastPrintTime = System.currentTimeMillis();
            DescribeInstancesRequest describeInstancesRequest = new DescribeInstancesRequest();
            List<String> instanceId = new ArrayList<>(1);
            instanceId.add(instance.getInstanceId());
            describeInstancesRequest.setInstanceIds(instanceId);
            DescribeInstancesResult describeInstancesResult;
            newInstance = instance;

            do {
                // we're waiting

                if (System.currentTimeMillis() - lastPrintTime >= Math.pow(2, retries) * 100) {
                    retries = retries + 1;
                    describeInstancesResult = client.describeInstances(describeInstancesRequest);
                    newInstance = describeInstancesResult.getReservations().get(0).getInstances().get(0);
                    lastPrintTime = System.currentTimeMillis();
                    if (newInstance.getState().getCode() != 16) {
                        FOKLogger.info(Main.class.getName(),
                                "Still waiting for the instance to boot, current instance state is "
                                        + newInstance.getState().getName());
                    }
                }
            } while (newInstance.getState().getCode() != 16);

            FOKLogger.info(Main.class.getName(), "Instance is " + newInstance.getState().getName());

            // generate the ssh ip of the instance
            String sshIp = newInstance.getPublicDnsName();

            FOKLogger.info(Main.class.getName(), "The instance id is " + newInstance.getInstanceId());
            FOKLogger.info(Main.class.getName(), "The instance ip is " + newInstance.getPublicIpAddress());
            FOKLogger.info(Main.class.getName(), "Connecting using ssh to " + sshUsername + "@" + sshIp);
            FOKLogger.info(Main.class.getName(),
                    "The instance will need some time to configure ssh on its end so some connection timeouts are normal");
            boolean retry;
            session = jsch.getSession(sshUsername, sshIp, 22);
            session.setConfig(sshConfig);
            do {
                try {
                    session.connect();
                    retry = false;
                } catch (Exception e) {
                    FOKLogger.info(Main.class.getName(), e.getClass().getName() + ": " + e.getMessage()
                            + ", retrying, Press Ctrl+C to cancel");
                    retry = true;
                }
            } while (retry);

            FOKLogger.info(Main.class.getName(),
                    "----------------------------------------------------------------------");
            FOKLogger.info(Main.class.getName(), "The following is the out- and input of the ssh session.");
            FOKLogger.info(Main.class.getName(), "Please note that out- and input may appear out of sync.");
            FOKLogger.info(Main.class.getName(),
                    "----------------------------------------------------------------------");

            PipedInputStream sshIn = new PipedInputStream();
            PipedOutputStream sshIn2 = new PipedOutputStream(sshIn);
            PrintStream sshInCommandStream = new PrintStream(sshIn2);
            Channel channel = session.openChannel("shell");
            channel.setInputStream(sshIn);
            channel.setOutputStream(new MyPrintStream());
            channel.connect();

            sshInCommandStream.print("yes\n");
            sshInCommandStream.print("yes\n");
            sshInCommandStream.print("1\n");
            sshInCommandStream.print("\n");
            sshInCommandStream.print("\n");
            sshInCommandStream.print("yes\n");
            sshInCommandStream.print("yes\n");
            sshInCommandStream.print("\n");
            sshInCommandStream.print("\n");
            sshInCommandStream.print("\n");
            sshInCommandStream.print("\n");
            sshInCommandStream.print("echo \"" + adminUsername + ":" + vpnPassword + "\" | sudo chpasswd\n");
            sshInCommandStream.print("exit\n");

            NullOutputStream nullOutputStream = new NullOutputStream();
            Thread watchForSSHDisconnectThread = new Thread(() -> {
                while (channel.isConnected()) {
                    nullOutputStream.write(0);
                }
                // disconnected
                cont();
            });
            watchForSSHDisconnectThread.setName("watchForSSHDisconnectThread");
            watchForSSHDisconnectThread.start();
        }
    } catch (JSchException | IOException e) {
        e.printStackTrace();
        if (session != null) {
            session.disconnect();
        }
        System.exit(1);
    }
}

From source file:com.liferay.amazontools.AMIBuilder.java

License:Open Source License

protected void start() {
    RunInstancesRequest runInstancesRequest = new RunInstancesRequest();

    String availabilityZone = properties.getProperty("availability.zone");

    if (!isZoneAvailable(availabilityZone)) {
        throw new RuntimeException("Unavailable zone " + availabilityZone);
    }//w  w  w . ja va2 s  .  c o  m

    String imageId = properties.getProperty("image.id");

    if (imageId == null) {
        imageId = getImageId(properties.getProperty("image.name"));
    }

    runInstancesRequest.setImageId(imageId);

    runInstancesRequest.setInstanceType(properties.getProperty("instance.type"));
    runInstancesRequest.setKeyName(properties.getProperty("key.name"));
    runInstancesRequest.setMaxCount(1);
    runInstancesRequest.setMinCount(1);

    Placement placement = new Placement();

    placement.setAvailabilityZone(availabilityZone);

    runInstancesRequest.setPlacement(placement);

    List<String> securityGroupsIds = new ArrayList<String>();

    securityGroupsIds.add(properties.getProperty("security.group.id"));

    runInstancesRequest.setSecurityGroupIds(securityGroupsIds);

    RunInstancesResult runInstancesResult = amazonEC2Client.runInstances(runInstancesRequest);

    Reservation reservation = runInstancesResult.getReservation();

    List<Instance> instances = reservation.getInstances();

    if (instances.isEmpty()) {
        throw new RuntimeException("Unable to create instances");
    }

    Instance instance = instances.get(0);

    _instanceId = instance.getInstanceId();
    _publicIpAddress = instance.getPublicIpAddress();

    StringBuilder sb = new StringBuilder(13);

    sb.append("{imageId=");
    sb.append(instance.getImageId());
    sb.append(", instanceId=");
    sb.append(_instanceId);
    sb.append(", instanceType=");
    sb.append(instance.getInstanceType());
    sb.append(", keyName=");
    sb.append(instance.getKeyName());
    sb.append(", reservationId=");
    sb.append(reservation.getReservationId());
    sb.append(", state=");

    InstanceState instanceState = instance.getState();

    sb.append(instanceState.getName());

    sb.append("}");

    System.out.println("Starting instance " + sb.toString());

    boolean running = false;

    for (int i = 0; i < 6; i++) {
        sleep(30);

        instance = getRunningInstance(_instanceId);

        if (instance != null) {
            _publicIpAddress = instance.getPublicIpAddress();

            running = true;

            sb = new StringBuilder(7);

            sb.append("{instanceId=");
            sb.append(_instanceId);
            sb.append(", publicIpAddress=");
            sb.append(_publicIpAddress);
            sb.append(", stat=");

            instanceState = instance.getState();

            sb.append(instanceState.getName());

            sb.append("}");

            System.out.println("Started instance " + sb.toString());

            break;
        }
    }

    if (!running) {
        throw new RuntimeException("Unable to start instance " + _instanceId);
    }
}

From source file:com.pinterest.arcee.aws.EC2HostInfoDAOImpl.java

License:Apache License

@Override
public List<HostBean> launchEC2Instances(GroupBean groupBean, int instanceCnt, String subnet) throws Exception {
    RunInstancesRequest request = new RunInstancesRequest();
    request.setImageId(groupBean.getImage_id());
    request.setInstanceType(groupBean.getInstance_type());
    request.setKeyName("ops");
    request.setSecurityGroupIds(Arrays.asList(groupBean.getSecurity_group()));
    request.setSubnetId(subnet);//from   w  w w .ja  v a  2s  . co m
    request.setUserData(groupBean.getUser_data());
    IamInstanceProfileSpecification iamRole = new IamInstanceProfileSpecification();
    iamRole.setArn(groupBean.getIam_role());
    request.setIamInstanceProfile(iamRole);
    request.setMinCount(instanceCnt);
    request.setMaxCount(instanceCnt);

    List<HostBean> newHosts = new ArrayList<>();
    try {
        RunInstancesResult result = ec2Client.runInstances(request);
        List<Instance> instances = result.getReservation().getInstances();
        LOG.info("Launch instances {}", instances.toString());
        for (Instance instance : instances) {
            HostBean host = new HostBean();
            host.setHost_name(instance.getInstanceId());
            host.setHost_id(instance.getInstanceId());
            host.setIp(instance.getPrivateIpAddress());
            host.setGroup_name(groupBean.getGroup_name());
            host.setState(HostState.PROVISIONED);
            host.setCreate_date(instance.getLaunchTime().getTime());
            host.setLast_update(instance.getLaunchTime().getTime());
            newHosts.add(host);
        }
    } catch (AmazonClientException ex) {
        LOG.error(String.format("Failed to call aws runInstances when launching host %s", newHosts.toString()),
                ex);
        throw new DeployInternalException(
                String.format("Failed to call aws runInstances when launching host %s", newHosts.toString()),
                ex);
    }
    return newHosts;
}

From source file:com.rmn.qa.aws.AwsVmManager.java

License:Open Source License

public List<Instance> launchNodes(final String amiId, final String instanceType, final int numberToStart,
        final String userData, final boolean terminateOnShutdown) throws NodesCouldNotBeStartedException {
    RunInstancesRequest runRequest = new RunInstancesRequest();
    runRequest.withImageId(amiId).withInstanceType(instanceType).withMinCount(numberToStart)
            .withMaxCount(numberToStart).withUserData(userData);
    if (terminateOnShutdown) {
        runRequest.withInstanceInitiatedShutdownBehavior("terminate");
    }/*  www . j a v a 2  s.  c o  m*/

    log.info("Setting image id: " + runRequest.getImageId());
    log.info("Setting instance type: " + runRequest.getInstanceType());

    Properties awsProperties = getAwsProperties();
    String subnetKey = awsProperties.getProperty(region + "_subnet_id");
    if (subnetKey != null) {
        log.info("Setting subnet: " + subnetKey);
        runRequest.withSubnetId(subnetKey);
    }

    String securityGroupKey = awsProperties.getProperty(region + "_security_group");
    if (securityGroupKey != null) {

        String[] splitSecurityGroupdIds = securityGroupKey.split(",");

        List securityGroupIdsAryLst = new ArrayList();
        for (int i = 0; i < splitSecurityGroupdIds.length; i++) {

            log.info("Setting security group(s): " + splitSecurityGroupdIds[i]);
            securityGroupIdsAryLst.add(splitSecurityGroupdIds[i]);
        }
        runRequest.setSecurityGroupIds(securityGroupIdsAryLst);
    }

    String keyName = awsProperties.getProperty(region + "_key_name");
    if (keyName != null) {
        log.info("Setting keyname:" + keyName);
        runRequest.withKeyName(keyName);
    }

    log.info("Sending run request to AWS...");

    RunInstancesResult runInstancesResult = getResults(runRequest, 0);
    log.info("Run request result returned.  Adding tags");

    // Tag the instances with the standard RMN AWS data
    List<Instance> instances = runInstancesResult.getReservation().getInstances();
    if (instances.size() == 0) {
        throw new NodesCouldNotBeStartedException(String.format(
                "Error starting up nodes -- count was zero and did not match expected count of %d",
                numberToStart));
    }

    associateTags(new Date().toString(), instances);
    return instances;
}

From source file:eu.optimis.interopt.provider.aws.AmazonClient.java

License:Apache License

@Override
public void deployService(String service_id, List<ServiceComponent> serviceComponents,
        XmlBeanServiceManifestDocument manifest) throws ServiceInstantiationException {

    AmazonEC2 ec2 = getAmazonEC2Client();

    log.info("Deploying service...");
    if (isDeployed(service_id)) {
        throw new ServiceInstantiationException(
                "This service is already deployed! " + "Terminate it before deploying it again.",
                new java.lang.Throwable());
    }/*from w w  w.j a v  a  2 s .  c o m*/
    // Get the number of VMs to deploy
    int totalVms = 0;

    for (ServiceComponent sc : serviceComponents) {
        totalVms = totalVms + sc.getInstances();
    }

    // If sum < maxvms invoke createVM method as many times as needed
    if (totalVms > AmazonClient.maxvms) {
        throw new ServiceInstantiationException("Number of VMs to deploy exceeds the maximum",
                new java.lang.Throwable());
    }

    for (ServiceComponent sc : serviceComponents) {
        int numInstances = sc.getInstances();
        log.info("Number of vm instances to deploy: " + numInstances);

        String imageId = sc.getImage();
        InstanceType type = selectInstanceType(sc);

        Placement placement = new Placement();
        placement.setAvailabilityZone(availabilityZone.getZoneName());
        RunInstancesRequest req = new RunInstancesRequest(imageId, numInstances, numInstances);
        ArrayList<String> securityGroups = new ArrayList<String>();
        securityGroups.add(SECURITY_GROUP);
        req.setSecurityGroupIds(securityGroups);
        req.setInstanceType(type);
        req.setPlacement(placement);
        //req.setMonitoring(true);
        try {
            RunInstancesResult res = ec2.runInstances(req);
            List<Instance> instances = res.getReservation().getInstances();
            log.info("Creating Tags...");
            for (Instance inst : instances) {
                Tag tag = new Tag("serviceid", service_id);
                List<Tag> tags = new ArrayList<Tag>();
                tags.add(tag);
                List<String> resources = new ArrayList<String>();
                resources.add(inst.getInstanceId());
                CreateTagsRequest req2 = new CreateTagsRequest(resources, tags);
                ec2.createTags(req2);
            }
        } catch (AmazonServiceException e) {
            log.error("Service deployment has failed: ");
            log.error(printServiceException(e));
            throw new ServiceInstantiationException("Service deployment has failed: " + e.getMessage(),
                    new java.lang.Throwable());
        }
        log.info("Service Deployed successfully!");
    }
}

From source file:hudson.plugins.ec2.SlaveTemplate.java

License:Open Source License

/**
 * Provisions an On-demand EC2 slave by launching a new instance or 
 * starting a previously-stopped instance.
 *//*from   www  .  j  a v a  2  s  .  c  o m*/
private EC2AbstractSlave provisionOndemand(TaskListener listener) throws AmazonClientException, IOException {
    PrintStream logger = listener.getLogger();
    AmazonEC2 ec2 = getParent().connect();

    try {
        String msg = "Launching " + ami + " for template " + description;
        logger.println(msg);
        LOGGER.info(msg);

        KeyPair keyPair = getKeyPair(ec2);

        RunInstancesRequest riRequest = new RunInstancesRequest(ami, 1, 1);
        InstanceNetworkInterfaceSpecification net = new InstanceNetworkInterfaceSpecification();

        if (useEphemeralDevices) {
            setupEphemeralDeviceMapping(riRequest);
        } else {
            setupCustomDeviceMapping(riRequest);
        }

        List<Filter> diFilters = new ArrayList<Filter>();
        diFilters.add(new Filter("image-id").withValues(ami));

        if (StringUtils.isNotBlank(getZone())) {
            Placement placement = new Placement(getZone());
            if (getUseDedicatedTenancy()) {
                placement.setTenancy("dedicated");
            }
            riRequest.setPlacement(placement);
            diFilters.add(new Filter("availability-zone").withValues(getZone()));
        }

        if (StringUtils.isNotBlank(getSubnetId())) {
            if (getAssociatePublicIp()) {
                net.setSubnetId(getSubnetId());
            } else {
                riRequest.setSubnetId(getSubnetId());
            }

            diFilters.add(new Filter("subnet-id").withValues(getSubnetId()));

            /* If we have a subnet ID then we can only use VPC security groups */
            if (!securityGroupSet.isEmpty()) {
                List<String> group_ids = getEc2SecurityGroups(ec2);

                if (!group_ids.isEmpty()) {
                    if (getAssociatePublicIp()) {
                        net.setGroups(group_ids);
                    } else {
                        riRequest.setSecurityGroupIds(group_ids);
                    }

                    diFilters.add(new Filter("instance.group-id").withValues(group_ids));
                }
            }
        } else {
            /* No subnet: we can use standard security groups by name */
            riRequest.setSecurityGroups(securityGroupSet);
            if (securityGroupSet.size() > 0)
                diFilters.add(new Filter("instance.group-name").withValues(securityGroupSet));
        }

        String userDataString = Base64.encodeBase64String(userData.getBytes());
        riRequest.setUserData(userDataString);
        riRequest.setKeyName(keyPair.getKeyName());
        diFilters.add(new Filter("key-name").withValues(keyPair.getKeyName()));
        riRequest.setInstanceType(type.toString());
        diFilters.add(new Filter("instance-type").withValues(type.toString()));

        if (getAssociatePublicIp()) {
            net.setAssociatePublicIpAddress(true);
            net.setDeviceIndex(0);
            riRequest.withNetworkInterfaces(net);
        }

        boolean hasCustomTypeTag = false;
        HashSet<Tag> inst_tags = null;
        if (tags != null && !tags.isEmpty()) {
            inst_tags = new HashSet<Tag>();
            for (EC2Tag t : tags) {
                inst_tags.add(new Tag(t.getName(), t.getValue()));
                diFilters.add(new Filter("tag:" + t.getName()).withValues(t.getValue()));
                if (StringUtils.equals(t.getName(), EC2Tag.TAG_NAME_JENKINS_SLAVE_TYPE)) {
                    hasCustomTypeTag = true;
                }
            }
        }
        if (!hasCustomTypeTag) {
            if (inst_tags == null) {
                inst_tags = new HashSet<Tag>();
            }
            inst_tags.add(new Tag(EC2Tag.TAG_NAME_JENKINS_SLAVE_TYPE, "demand"));
        }

        DescribeInstancesRequest diRequest = new DescribeInstancesRequest();
        diFilters.add(new Filter("instance-state-name").withValues(InstanceStateName.Stopped.toString(),
                InstanceStateName.Stopping.toString()));
        diRequest.setFilters(diFilters);

        msg = "Looking for existing instances with describe-instance: " + diRequest;
        logger.println(msg);
        LOGGER.fine(msg);

        DescribeInstancesResult diResult = ec2.describeInstances(diRequest);

        Instance existingInstance = null;
        if (StringUtils.isNotBlank(getIamInstanceProfile())) {
            riRequest.setIamInstanceProfile(
                    new IamInstanceProfileSpecification().withArn(getIamInstanceProfile()));
            // cannot filter on IAM Instance Profile, so search in result
            reservationLoop: for (Reservation reservation : diResult.getReservations()) {
                for (Instance instance : reservation.getInstances()) {
                    if (instance.getIamInstanceProfile() != null
                            && instance.getIamInstanceProfile().getArn().equals(getIamInstanceProfile())) {
                        existingInstance = instance;
                        break reservationLoop;
                    }
                }
            }
        } else if (diResult.getReservations().size() > 0) {
            existingInstance = diResult.getReservations().get(0).getInstances().get(0);
        }

        if (existingInstance == null) {
            // Have to create a new instance
            Instance inst = ec2.runInstances(riRequest).getReservation().getInstances().get(0);

            /* Now that we have our instance, we can set tags on it */
            if (inst_tags != null) {
                for (int i = 0; i < 5; i++) {
                    try {
                        updateRemoteTags(ec2, inst_tags, inst.getInstanceId());
                        break;
                    } catch (AmazonServiceException e) {
                        if (e.getErrorCode().equals("InvalidInstanceRequestID.NotFound")) {
                            Thread.sleep(5000);
                            continue;
                        }
                        throw e;
                    }
                }

                // That was a remote request - we should also update our local instance data.
                inst.setTags(inst_tags);
            }
            msg = "No existing instance found - created: " + inst;
            logger.println(msg);
            LOGGER.info(msg);
            return newOndemandSlave(inst);
        }

        msg = "Found existing stopped instance: " + existingInstance;
        logger.println(msg);
        LOGGER.info(msg);

        List<String> instances = new ArrayList<String>();
        instances.add(existingInstance.getInstanceId());
        StartInstancesRequest siRequest = new StartInstancesRequest(instances);
        StartInstancesResult siResult = ec2.startInstances(siRequest);

        msg = "Starting existing instance: " + existingInstance + " result:" + siResult;
        logger.println(msg);
        LOGGER.fine(msg);

        for (EC2AbstractSlave ec2Node : NodeIterator.nodes(EC2AbstractSlave.class)) {
            if (ec2Node.getInstanceId().equals(existingInstance.getInstanceId())) {
                msg = "Found existing corresponding Jenkins slave: " + ec2Node;
                logger.println(msg);
                LOGGER.finer(msg);
                return ec2Node;
            }
        }

        // Existing slave not found
        msg = "Creating new Jenkins slave for existing instance: " + existingInstance;
        logger.println(msg);
        LOGGER.info(msg);
        return newOndemandSlave(existingInstance);

    } catch (FormException e) {
        throw new AssertionError(); // we should have discovered all configuration issues upfront
    } catch (InterruptedException e) {
        throw new RuntimeException(e);
    }
}

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

License:Apache License

@ResponseBody
@RequestMapping(value = "instance", method = RequestMethod.POST)
public Status spotInstance(@RequestBody InstanceModel instance) {
    if (amazonEC2 == null)
        throw new AmazonServiceException("Amazon service can't initialize");
    if (!instance.isValid())
        throw new AmazonServiceException("Invalid message");

    RunInstancesRequest runInstancesRequest = new RunInstancesRequest();
    runInstancesRequest.setInstanceType(instance.getInstanceType());
    runInstancesRequest.setImageId(instance.getAmi());
    runInstancesRequest.setMinCount(1);/*  w w w .  j av  a  2s  .c o m*/
    runInstancesRequest.setMaxCount(1);
    runInstancesRequest.setKeyName(instance.getKey());
    runInstancesRequest.setSecurityGroupIds(Arrays.asList(instance.getSecurityGroup()));

    amazonEC2.runInstances(runInstancesRequest);

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

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  ww.  j a  v a  2 s. com
    }

    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);
}