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

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

Introduction

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

Prototype


public void setInstanceType(InstanceType instanceType) 

Source Link

Document

The instance type.

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);/*from ww  w. j a  va2 s .co  m*/
    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 {
        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:advanced.Requests.java

License:Open Source License

public void launchOnDemand() {
    //============================================================================================//
    //====================================== Launch an On-Demand Instance ========================// 
    //====================================== If we Didn't Get a Spot Instance ====================// 
    //============================================================================================//

    // Setup the request for 1 x t1.micro using the same security group and 
    // AMI id as the Spot request.
    RunInstancesRequest runInstancesRequest = new RunInstancesRequest();
    runInstancesRequest.setInstanceType(instanceType);
    runInstancesRequest.setImageId(amiID);
    runInstancesRequest.setMinCount(Integer.valueOf(1));
    runInstancesRequest.setMaxCount(Integer.valueOf(1));

    // Add the security group to the request.
    ArrayList<String> securityGroups = new ArrayList<String>();
    securityGroups.add(securityGroup);/* ww w. ja  v a  2 s  .co  m*/
    runInstancesRequest.setSecurityGroups(securityGroups);

    // Launch the instance.
    RunInstancesResult runResult = ec2.runInstances(runInstancesRequest);

    // Add the instance id into the instance id list, so we can potentially later
    // terminate that list.
    for (Instance instance : runResult.getReservation().getInstances()) {
        System.out.println("Launched On-Demand Instace: " + instance.getInstanceId());
        instanceIds.add(instance.getInstanceId());
    }
}

From source file:br.unb.cic.bionimbuz.elasticity.legacy.Ec2Commands.java

License:Open Source License

public static void createinstance() throws IOException {
    Ec2Commands.setup();/*from w  ww .j  a va 2  s  . com*/

    try {

        System.out.println("Criando nova maquina BioninbuZ");
        String imageId;
        System.out.println("Enter the image AMI id (eg: ami-687b4f2d)");
        imageId = user_input.next();

        int minInstanceCount = 1; // 
        int maxInstanceCount = 1;
        RunInstancesRequest rir = new RunInstancesRequest(imageId, minInstanceCount, maxInstanceCount);
        rir.setInstanceType("t1.micro");

        Scanner keyscan = new Scanner(System.in);
        System.out.println("Do you want to use an existing keypair or do you want to create a new one?");
        System.out.println("#1 Use existing keypair");
        System.out.println("#2 Create a new keypair");
        int keypairoption;
        String key; //existing keypair name
        keypairoption = keyscan.nextInt();
        if (keypairoption == 1) {
            System.out.println("Enter the existing keypair name to use with the new instance");
            key = keyscan.next();
            rir.withKeyName(key);
        } else if (keypairoption == 2) {
            //count++;
            System.out.println("Enter the keypair name to create");
            String newkeyname;
            newkeyname = keyscan.next();
            CreateKeyPairRequest newKeyRequest = new CreateKeyPairRequest();
            newKeyRequest.setKeyName(newkeyname);
            CreateKeyPairResult keyresult = EC2.createKeyPair(newKeyRequest);

            keyPair = keyresult.getKeyPair();
            System.out.println("The key we created is = " + keyPair.getKeyName() + "\nIts fingerprint is="
                    + keyPair.getKeyFingerprint() + "\nIts material is= \n" + keyPair.getKeyMaterial());

            System.out.println(
                    "Enter the directory to store .pem file (eg: Windows C:\\Users\\user\\Desktop\\, Linux /user/home)");
            String dir;
            dir = keyscan.next();
            String fileName = dir + newkeyname + ".pem";
            File distFile = new File(fileName);
            BufferedReader bufferedReader = new BufferedReader(new StringReader(keyPair.getKeyMaterial()));
            BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(distFile));
            char buf[] = new char[1024];
            int len;
            while ((len = bufferedReader.read(buf)) != -1) {
                bufferedWriter.write(buf, 0, len);
            }
            bufferedWriter.flush();
            bufferedReader.close();
            bufferedWriter.close();

        }

        rir.withSecurityGroups("default");

        RunInstancesResult result = EC2.runInstances(rir);

        System.out.println("waiting");
        try {
            Thread.sleep(50000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        System.out.println("OK");

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

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

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

        }

        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        System.out.println();
        System.out.println("Restarting the application");
        System.out.println();
        //    Ec2Commands.enteroption();   
    } catch (AmazonServiceException ase) {
        System.out.println("Caught Exception: " + ase.getMessage());
        System.out.println("Reponse Status Code: " + ase.getStatusCode());
        System.out.println("Error Code: " + ase.getErrorCode());
        System.out.println("Request ID: " + ase.getRequestId());
        System.out.println("Give a valid input");
        System.out.println("");
        //      Ec2Commands.enteroption();
    }

}

From source file:br.unb.cic.bionimbuz.services.elasticity.Ec2Commands.java

License:Open Source License

public static void createinstance() throws IOException {
    Ec2Commands.setup();/*  w w  w .  j av  a  2s  . co m*/

    try {

        System.out.println("Criando nova maquina BioninbuZ");
        String imageId;
        System.out.println("Enter the image AMI id (eg: ami-687b4f2d)");
        imageId = user_input.next();

        int minInstanceCount = 1; // 
        int maxInstanceCount = 1;
        RunInstancesRequest rir = new RunInstancesRequest(imageId, minInstanceCount, maxInstanceCount);
        rir.setInstanceType("t1.micro");

        try (Scanner keyscan = new Scanner(System.in)) {
            System.out.println("Do you want to use an existing keypair or do you want to create a new one?");
            System.out.println("#1 Use existing keypair");
            System.out.println("#2 Create a new keypair");
            int keypairoption;
            String key; //existing keypair name
            keypairoption = keyscan.nextInt();
            if (keypairoption == 1) {
                System.out.println("Enter the existing keypair name to use with the new instance");
                key = keyscan.next();
                rir.withKeyName(key);
            } else if (keypairoption == 2) {
                //count++;
                System.out.println("Enter the keypair name to create");
                String newkeyname;
                newkeyname = keyscan.next();
                CreateKeyPairRequest newKeyRequest = new CreateKeyPairRequest();
                newKeyRequest.setKeyName(newkeyname);
                CreateKeyPairResult keyresult = EC2.createKeyPair(newKeyRequest);

                keyPair = keyresult.getKeyPair();
                System.out.println("The key we created is = " + keyPair.getKeyName() + "\nIts fingerprint is="
                        + keyPair.getKeyFingerprint() + "\nIts material is= \n" + keyPair.getKeyMaterial());

                System.out.println(
                        "Enter the directory to store .pem file (eg: Windows C:\\Users\\user\\Desktop\\, Linux /user/home)");
                String dir;
                dir = keyscan.next();
                String fileName = dir + newkeyname + ".pem";
                File distFile = new File(fileName);
                BufferedReader bufferedReader = new BufferedReader(new StringReader(keyPair.getKeyMaterial()));
                BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(distFile));
                char buf[] = new char[1024];
                int len;
                while ((len = bufferedReader.read(buf)) != -1) {
                    bufferedWriter.write(buf, 0, len);
                }
                bufferedWriter.flush();
                bufferedReader.close();
                bufferedWriter.close();

            }
        }

        rir.withSecurityGroups("default");

        RunInstancesResult result = EC2.runInstances(rir);

        System.out.println("waiting");
        try {
            Thread.sleep(50000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        System.out.println("OK");

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

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

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

        }

        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        System.out.println();
        System.out.println("Restarting the application");
        System.out.println();
        //    Ec2Commands.enteroption();   
    } catch (AmazonServiceException ase) {
        System.out.println("Caught Exception: " + ase.getMessage());
        System.out.println("Reponse Status Code: " + ase.getStatusCode());
        System.out.println("Error Code: " + ase.getErrorCode());
        System.out.println("Request ID: " + ase.getRequestId());
        System.out.println("Give a valid input");
        System.out.println("");
        //      Ec2Commands.enteroption();
    }

}

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

License:Apache License

public IMachine createMachine(IComputeCenter computeCenter, IImage image, IMachineDescriptor machineDescriptor)
        throws InvalidObjectException, ConnectorException {
    boolean succeeded = false;
    Exception createFailureRootCause = null;
    Instance instance = null;// ww  w  .ja va 2s. co  m

    try {
        IProperty[] macProps = machineDescriptor.getProperties();

        AmazonEC2 connector = getConnector(image, computeCenter, controllerServices);
        String amiName = Utils.getAMIName(image.getProperties(), controllerServices);
        List<String> securityGroups = getSecurityGroup(macProps);
        validateAndConfigureSecurityGroups(securityGroups, connector);

        controllerServices.getStringPropertyByName(macProps, Utils.SECURITY_GROUP)
                .setValue(getSecurityGroupsAsString(securityGroups));

        String keyPair = Utils.getKeyPair(macProps, controllerServices);

        InstanceType instanceType = getInstanceType(macProps);

        String zone = Utils.getZone(macProps, controllerServices);
        String kernel = Utils.getKernel(macProps, controllerServices);
        String ramdisk = Utils.getRamDisk(macProps, controllerServices);

        String controllerHost = System.getProperty(CONTROLLER_SERVICES_HOST_NAME_PROPERTY_KEY,
                InetAddress.getLocalHost().getHostName());

        int controllerPort = Integer.getInteger(CONTROLLER_SERVICES_PORT_PROPERTY_KEY,
                DEFAULT_CONTROLLER_PORT_VALUE);

        IAccount account = computeCenter.getAccount();

        String accountName = account.getName();
        String accountAccessKey = account.getAccessKey();

        AgentResolutionEncoder agentResolutionEncoder = new AgentResolutionEncoder(controllerHost,
                controllerPort, accountName, accountAccessKey);

        String userData = agentResolutionEncoder.encodeAgentResolutionInfo();

        String instanceName = Utils.getInstanceName(macProps, controllerServices);

        logger.info("Starting EC2 machine of Image :" + amiName + " Name :" + instanceName + " security :"
                + securityGroups + " keypair :" + keyPair + " instance :" + instanceType + " zone :" + zone
                + " kernel :" + kernel + " ramdisk :" + ramdisk + " userData :" + userData);

        RunInstancesRequest runInstancesRequest = new RunInstancesRequest(amiName, 1, 1);
        runInstancesRequest.setSecurityGroups(securityGroups);
        runInstancesRequest.setUserData(Base64.encodeAsString(userData.getBytes()));
        runInstancesRequest.setKeyName(keyPair);
        runInstancesRequest.setInstanceType(instanceType);
        runInstancesRequest.setKernelId(kernel);
        runInstancesRequest.setRamdiskId(ramdisk);

        Reservation reservation = connector.runInstances(runInstancesRequest).getReservation();
        List<Instance> instances = reservation.getInstances();

        if (instances.size() == 0)
            throw new ConnectorException("Cannot create instance for image :" + image.getName());

        instance = instances.get(0);

        //Set name for the instance
        if (!Strings.isNullOrEmpty(instanceName)) {
            CreateTagsRequest createTagsRequest = new CreateTagsRequest();
            createTagsRequest.withResources(instance.getInstanceId()).withTags(new Tag("Name", instanceName));
            connector.createTags(createTagsRequest);
        }

        logger.info("EC2 machine started; id:" + instance.getInstanceId());

        IMachine machine;

        if (Strings.isNullOrEmpty(instance.getPublicDnsName())) {
            machine = controllerServices.createMachineInstance(instance.getInstanceId(),
                    agentResolutionEncoder.getUniqueHostIdentifier(), computeCenter, machineDescriptor, image,
                    getAgentPort());
        } else {
            machine = controllerServices.createMachineInstance(instance.getInstanceId(),
                    agentResolutionEncoder.getUniqueHostIdentifier(), instance.getPublicDnsName(),
                    computeCenter, machineDescriptor, image, getAgentPort());
        }

        if (kernel == null) {
            controllerServices.getStringPropertyByName(macProps, Utils.KERNEL).setValue(instance.getKernelId());
        }

        if (zone == null) {
            DescribeAvailabilityZonesResult describeAvailabilityZonesResult = connector
                    .describeAvailabilityZones();
            List<AvailabilityZone> availabilityZones = describeAvailabilityZonesResult.getAvailabilityZones();
            controllerServices.getStringPropertyByName(macProps, Utils.ZONE)
                    .setValue(availabilityZones.get(0).getZoneName());
        }

        controllerServices.getStringPropertyByName(macProps, Utils.INSTANCE_TYPE)
                .setValue(instance.getInstanceType());

        succeeded = true;

        return machine;

    } catch (InvalidObjectException e) {
        createFailureRootCause = e;
        throw e;
    } catch (ConnectorException e) {
        createFailureRootCause = e;
        throw e;
    } catch (Exception e) {
        createFailureRootCause = e;
        throw new ConnectorException(e.getMessage(), e);
    } finally {
        // We have to make sure to terminate any orphan EC2 instances if 
        // the machine create fails.
        if (!succeeded && instance != null) {
            try {
                ConnectorLocator.getInstance().getConnector(computeCenter, controllerServices)
                        .terminateInstances(
                                new TerminateInstancesRequest(Lists.newArrayList(instance.getInstanceId())));
            } catch (Exception e) {
                throw new ConnectorException("Machine create failed, but terminate failed as well! "
                        + "We have an orphan EC2 instance with id: " + instance.getInstanceId()
                        + " that must be shut down manually. Root cause for machine "
                        + "create failure is following: ", createFailureRootCause);
            }
        }
    }
}

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

License:Apache License

public static Optional<Instance> onDemandInstance(AmazonEC2 ec2Client, Optional<Image> image, Integer minCount,
        Integer maxCount, SecurityGroupInformation securityGroupInformation,
        KeyPairInformation keyPairInformation, Optional<String> instanceType, Optional<String> availabilityZone,
        Long sleep) {// w w w . java 2 s. c om
    if (!image.isPresent()) {
        return Optional.absent();
    }

    RunInstancesRequest runInstancesRequest = new RunInstancesRequest().withImageId(image.get().getImageId())
            .withMinCount(minCount).withMaxCount(maxCount)
            .withSecurityGroups(securityGroupInformation.getGroupName())
            .withKeyName(keyPairInformation.getName());

    log.info("ImageId=" + image.get().getImageId());
    log.info("MinCount=" + minCount);
    log.info("MaxCount=" + maxCount);
    log.info("SecurityGroups.1=" + securityGroupInformation.getGroupName());
    log.info("KeyName=" + keyPairInformation.getName());

    if (instanceType.isPresent()) {
        runInstancesRequest.setInstanceType(instanceType.get());
        log.info("InstanceType=" + instanceType.get());
    }

    if (availabilityZone.isPresent()) {
        runInstancesRequest.setPlacement(new Placement().withAvailabilityZone(availabilityZone.get()));

        log.info("Placement.AvailabilityZone=" + availabilityZone.get());
    }

    RunInstancesResult runInstancesResult = ec2Client.runInstances(runInstancesRequest);

    DescribeInstanceStatusRequest describeInstanceStatusRequest = new DescribeInstanceStatusRequest()
            .withInstanceIds(runInstancesResult.getReservation().getInstances().get(0).getInstanceId());

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

            DescribeInstanceStatusResult describeInstanceStatusResult = ec2Client
                    .describeInstanceStatus(describeInstanceStatusRequest);
            if (describeInstanceStatusResult.getInstanceStatuses().isEmpty()) {
                continue;
            }
            InstanceStatus instance = describeInstanceStatusResult.getInstanceStatuses().get(0);

            String instanceState = instance.getInstanceState().getName();

            log.info("instanceState = " + instanceState);

            if ("pending".equals(instanceState)) {
                continue;
            }

            if (!"running".equals(instanceState)) {
                return Optional.absent();
            }

            String instanceStatus = instance.getInstanceStatus().getStatus();
            String systemStatus = instance.getSystemStatus().getStatus();

            log.info("instanceStatus = " + instanceStatus);
            log.info("systemStatus = " + systemStatus);

            if ("impaired".equals(instanceStatus)) {
                return Optional.absent();
            }

            if ("impaired".equals(systemStatus)) {
                return Optional.absent();
            }

            if (!"ok".equals(instanceStatus)) {
                continue;
            }

            if (!"ok".equals(systemStatus)) {
                continue;
            }

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

    DescribeInstancesResult describeInstancesResult = ec2Client.describeInstances(new DescribeInstancesRequest()
            .withInstanceIds(runInstancesResult.getReservation().getInstances().get(0).getInstanceId()));

    return Optional.fromNullable(describeInstancesResult.getReservations().get(0).getInstances().get(0));
}

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/*from  w w  w.j  a v  a2  s  . 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.hpcloud.daas.ec2.AwsConsoleApp.java

License:Open Source License

public static void CreateNewInstance(String imageId, String instanceType, List<String> securityGroups,
        String userData) {//w ww .  j a  v a 2 s  . c om
    try {
        RunInstancesRequest crir = new RunInstancesRequest();
        crir.setImageId(imageId);

        crir.setInstanceType(instanceType);
        crir.setSecurityGroups(securityGroups);

        crir.setKeyName("hpdefault");

        if (userData != null) {
            crir.setUserData(userData);
        }

        RunInstancesResult result = ec2.runInstances(crir);
        System.out.println(result);

        String instanceId = null;
        List<Instance> instances = result.getReservation().getInstances();
        for (Instance instance : instances) {
            instanceId = instance.getInstanceId();
        }

        // HACKHACK sleep for 5 seconds so the private ip gets assigned
        System.out.println("Sleeping for 5 to wait for the private ip");
        try {
            Thread.sleep(5000);
        } catch (InterruptedException ignore) {
            ignore.printStackTrace();
        }

        String publicIp = assignPublicIp(instanceId);

        System.out.println("Public IP: " + publicIp);

        System.out.println("Instance State: " + getInstanceState(instanceId));

    } catch (AmazonServiceException ase) {
        System.out.println("Caught Exception: " + ase.getMessage());
        System.out.println("Reponse Status Code: " + ase.getStatusCode());
        System.out.println("Error Code: " + ase.getErrorCode());
        System.out.println("Request ID: " + ase.getRequestId());
    }
}

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);
    }//from  w  ww.j a  v a 2  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.norbl.cbp.ppe.Ec2Wrangler.java

License:Open Source License

/** This version of <tt>launchInstances()</tt> gets all
 *  parameters from method arguments. //from   w  w w .j a va 2s  . co m
 *        
  * @param instanceType
  * @param imageID
  * @param availabilityZone
  * @param minInstances
  * @param maxInstances
  * @param keyName
  * @param securityGroupName
  * @param networkName
  * @param userData
  * @return
  * @throws MissingParamsException
  * @throws ImproperParamException 
  */
public String launchInstances(InstanceType instanceType, String imageID, String availabilityZone,
        int minInstances, int maxInstances, String keyName, String securityGroupName, String networkName,
        String userData) throws MissingParamsException, ImproperParamException {

    if ((minInstances < 1) || (maxInstances < minInstances))
        throw new ImproperParamException("instances min=" + minInstances + " max=" + maxInstances);

    RunInstancesRequest req = new RunInstancesRequest();
    req.setInstanceType(instanceType);
    req.setImageId(imageID);
    if (Ec2Location.isValidAvailablityZone(ec2Client, availabilityZone))
        setAvailabilityZone(req, availabilityZone);
    // else any zone will do, so don't set it.
    req.setMinCount(minInstances);
    req.setMaxCount(maxInstances);
    req.setKeyName(keyName);
    List<String> sgs = new ArrayList<String>();
    sgs.add(securityGroupName);
    req.setSecurityGroups(sgs);
    req.setUserData(Base64.encodeBase64String(userData.getBytes()));

    String networkID = NiM.createNetworkID();
    NetworkInfo ni = new NetworkInfo(networkID, networkName);
    NiM.register(ni);
    ni.setState(NetworkInfo.State.pending);

    if (isHVM(imageID))
        setupClusterPlacementGroup(req);

    RunInstancesResult rr = ec2Client.runInstances(req);

    NiM.update(this); // Update the network info

    waitForAllInstancesToBeRunning(rr);

    tagInstances(getInstanceIDs(rr), networkID, networkName);

    NiM.update(getInstancesAllListed()); // Update the network info

    return (networkID);
}