Example usage for com.amazonaws AmazonClientException AmazonClientException

List of usage examples for com.amazonaws AmazonClientException AmazonClientException

Introduction

In this page you can find the example usage for com.amazonaws AmazonClientException AmazonClientException.

Prototype

public AmazonClientException(Throwable t) 

Source Link

Usage

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

License:Open Source License

/**
 * Provision a new slave for an EC2 spot instance to call back to Jenkins
 *///from ww  w. j a  va  2  s  . c o m
private EC2AbstractSlave provisionSpot(TaskListener listener) throws AmazonClientException, IOException {
    PrintStream logger = listener.getLogger();
    AmazonEC2 ec2 = getParent().connect();

    try {
        logger.println("Launching " + ami + " for template " + description);
        KeyPair keyPair = getKeyPair(ec2);

        RequestSpotInstancesRequest spotRequest = new RequestSpotInstancesRequest();

        // Validate spot bid before making the request
        if (getSpotMaxBidPrice() == null) {
            // throw new FormException("Invalid Spot price specified: " + getSpotMaxBidPrice(), "spotMaxBidPrice");
            throw new AmazonClientException("Invalid Spot price specified: " + getSpotMaxBidPrice());
        }

        spotRequest.setSpotPrice(getSpotMaxBidPrice());
        spotRequest.setInstanceCount(Integer.valueOf(1));
        spotRequest.setType(getBidType());

        LaunchSpecification launchSpecification = new LaunchSpecification();
        InstanceNetworkInterfaceSpecification net = new InstanceNetworkInterfaceSpecification();

        launchSpecification.setImageId(ami);
        launchSpecification.setInstanceType(type);

        if (StringUtils.isNotBlank(getZone())) {
            SpotPlacement placement = new SpotPlacement(getZone());
            launchSpecification.setPlacement(placement);
        }

        if (StringUtils.isNotBlank(getSubnetId())) {
            if (getAssociatePublicIp()) {
                net.setSubnetId(getSubnetId());
            } else {
                launchSpecification.setSubnetId(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 {
                        ArrayList<GroupIdentifier> groups = new ArrayList<GroupIdentifier>();

                        for (String group_id : group_ids) {
                            GroupIdentifier group = new GroupIdentifier();
                            group.setGroupId(group_id);
                            groups.add(group);
                        }
                        if (!groups.isEmpty())
                            launchSpecification.setAllSecurityGroups(groups);
                    }
                }
            }
        } else {
            /* No subnet: we can use standard security groups by name */
            if (securityGroupSet.size() > 0)
                launchSpecification.setSecurityGroups(securityGroupSet);
        }

        // The slave must know the Jenkins server to register with as well
        // as the name of the node in Jenkins it should register as. The only
        // way to give information to the Spot slaves is through the ec2 user data
        String jenkinsUrl = Hudson.getInstance().getRootUrl();
        // We must provide a unique node name for the slave to connect to Jenkins.
        // We don't have the EC2 generated instance ID, or the Spot request ID
        // until after the instance is requested, which is then too late to set the
        // user-data for the request. Instead we generate a unique name from UUID
        // so that the slave has a unique name within Jenkins to register to.
        String slaveName = UUID.randomUUID().toString();
        String newUserData = "";

        // We want to allow node configuration with cloud-init and user-data,
        // while maintaining backward compatibility with old ami's
        // The 'new' way is triggered by the presence of '${SLAVE_NAME}'' in the user data 
        // (which is not too much to ask)
        if (userData.contains("${SLAVE_NAME}")) {
            // The cloud-init compatible way
            newUserData = new String(userData);
            newUserData = newUserData.replace("${SLAVE_NAME}", slaveName);
            newUserData = newUserData.replace("${JENKINS_URL}", jenkinsUrl);
        } else {
            // The 'old' way - maitain full backward compatibility
            newUserData = "JENKINS_URL=" + jenkinsUrl + "&SLAVE_NAME=" + slaveName + "&USER_DATA="
                    + Base64.encodeBase64String(userData.getBytes());
        }

        String userDataString = Base64.encodeBase64String(newUserData.getBytes());

        launchSpecification.setUserData(userDataString);
        launchSpecification.setKeyName(keyPair.getKeyName());
        launchSpecification.setInstanceType(type.toString());

        if (getAssociatePublicIp()) {
            net.setAssociatePublicIpAddress(true);
            net.setDeviceIndex(0);
            launchSpecification.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()));
                if (StringUtils.equals(t.getName(), EC2Tag.TAG_NAME_JENKINS_SLAVE_TYPE)) {
                    hasCustomTypeTag = true;
                }
            }
        }
        if (!hasCustomTypeTag) {
            inst_tags.add(new Tag(EC2Tag.TAG_NAME_JENKINS_SLAVE_TYPE, "spot"));
        }

        if (StringUtils.isNotBlank(getIamInstanceProfile())) {
            launchSpecification.setIamInstanceProfile(
                    new IamInstanceProfileSpecification().withArn(getIamInstanceProfile()));
        }

        spotRequest.setLaunchSpecification(launchSpecification);

        // Make the request for a new Spot instance
        RequestSpotInstancesResult reqResult = ec2.requestSpotInstances(spotRequest);

        List<SpotInstanceRequest> reqInstances = reqResult.getSpotInstanceRequests();
        if (reqInstances.size() <= 0) {
            throw new AmazonClientException("No spot instances found");
        }

        SpotInstanceRequest spotInstReq = reqInstances.get(0);
        if (spotInstReq == null) {
            throw new AmazonClientException("Spot instance request is null");
        }

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

            // That was a remote request - we should also update our local instance data.
            spotInstReq.setTags(inst_tags);
        }

        logger.println("Spot instance id in provision: " + spotInstReq.getSpotInstanceRequestId());

        return newSpotSlave(spotInstReq, slaveName);

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

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

License:Open Source License

/**
 * Get a KeyPair from the configured information for the slave template
 *//*  ww  w . ja va  2  s. c  o m*/
private KeyPair getKeyPair(AmazonEC2 ec2) throws IOException, AmazonClientException {
    KeyPair keyPair = parent.getPrivateKey().find(ec2);
    if (keyPair == null) {
        throw new AmazonClientException(
                "No matching keypair found on EC2. Is the EC2 private key a valid one?");
    }
    return keyPair;
}

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

License:Open Source License

/**
 * Get a list of security group ids for the slave
 *///from   ww  w . ja v  a 2 s  .  c  om
private List<String> getEc2SecurityGroups(AmazonEC2 ec2) throws AmazonClientException {
    List<String> group_ids = new ArrayList<String>();

    DescribeSecurityGroupsResult group_result = getSecurityGroupsBy("group-name", securityGroupSet, ec2);
    if (group_result.getSecurityGroups().size() == 0) {
        group_result = getSecurityGroupsBy("group-id", securityGroupSet, ec2);
    }

    for (SecurityGroup group : group_result.getSecurityGroups()) {
        if (group.getVpcId() != null && !group.getVpcId().isEmpty()) {
            List<Filter> filters = new ArrayList<Filter>();
            filters.add(new Filter("vpc-id").withValues(group.getVpcId()));
            filters.add(new Filter("state").withValues("available"));
            filters.add(new Filter("subnet-id").withValues(getSubnetId()));

            DescribeSubnetsRequest subnet_req = new DescribeSubnetsRequest();
            subnet_req.withFilters(filters);
            DescribeSubnetsResult subnet_result = ec2.describeSubnets(subnet_req);

            List<Subnet> subnets = subnet_result.getSubnets();
            if (subnets != null && !subnets.isEmpty()) {
                group_ids.add(group.getGroupId());
            }
        }
    }

    if (securityGroupSet.size() != group_ids.size()) {
        throw new AmazonClientException(
                "Security groups must all be VPC security groups to work in a VPC context");
    }

    return group_ids;
}

From source file:hudson.plugins.ec2.ssh.EC2SpotUnixLauncher.java

License:Open Source License

private Connection connectToSsh(final EC2Computer computer, final PrintStream logger)
        throws AmazonClientException, InterruptedException {
    final long timeout = computer.getNode().getLaunchTimeoutInMillis();
    final long startTime = System.currentTimeMillis();
    while (true) {
        try {/*from www  . ja va2  s .  c o m*/
            final long waitTime = System.currentTimeMillis() - startTime;
            if (timeout > 0 && waitTime > timeout) {
                throw new AmazonClientException("Timed out after " + (waitTime / 1000)
                        + " seconds of waiting for ssh to become available. (maximum timeout configured is "
                        + (timeout / 1000) + ")");
            }
            final Instance instance = computer.updateInstanceDescription();
            final String vpc_id = instance.getVpcId();
            String host;

            if (computer.getNode().usePrivateDnsName) {
                host = instance.getPrivateDnsName();
            } else {
                host = instance.getPublicDnsName();
                // If we fail to get a public DNS name, use the private IP.
                if (host == null || host.equals("")) {
                    host = instance.getPrivateIpAddress();
                }
            }

            if ("0.0.0.0".equals(host)) {
                logger.println("Invalid host 0.0.0.0, your host is most likely waiting for an ip address.");
                throw new IOException("goto sleep");
            }

            final int port = computer.getSshPort();
            final Integer slaveConnectTimeout = Integer.getInteger("jenkins.ec2.slaveConnectTimeout", 10000);
            logger.println("Connecting to " + host + " on port " + port + ", with timeout "
                    + slaveConnectTimeout + ".");
            final Connection conn = new Connection(host, port);
            final ProxyConfiguration proxyConfig = Jenkins.getInstance().proxy;
            final Proxy proxy = proxyConfig == null ? Proxy.NO_PROXY : proxyConfig.createProxy(host);
            if (!proxy.equals(Proxy.NO_PROXY) && proxy.address() instanceof InetSocketAddress) {
                final InetSocketAddress address = (InetSocketAddress) proxy.address();
                HTTPProxyData proxyData = null;
                if (null != proxyConfig.getUserName()) {
                    proxyData = new HTTPProxyData(address.getHostName(), address.getPort(),
                            proxyConfig.getUserName(), proxyConfig.getPassword());
                } else {
                    proxyData = new HTTPProxyData(address.getHostName(), address.getPort());
                }
                conn.setProxyData(proxyData);
            }
            // currently OpenSolaris offers no way of verifying the host certificate, so just accept it blindly,
            // hoping that no man-in-the-middle attack is going on.
            conn.connect(new ServerHostKeyVerifier() {
                public boolean verifyServerHostKey(final String hostname, final int port,
                        final String serverHostKeyAlgorithm, final byte[] serverHostKey) throws Exception {
                    return true;
                }
            }, slaveConnectTimeout, slaveConnectTimeout);
            logger.println("Connected via SSH.");
            return conn; // successfully connected
        } catch (final IOException e) {
            // keep retrying until SSH comes up
            logger.println("Waiting for SSH to come up. Sleeping 5.");
            Thread.sleep(5000);
        }
    }
}

From source file:hudson.plugins.ec2.ssh.EC2UnixLauncher.java

License:Open Source License

private Connection connectToSsh(EC2Computer computer, PrintStream logger)
        throws AmazonClientException, InterruptedException {
    final long timeout = computer.getNode().getLaunchTimeoutInMillis();
    final long startTime = System.currentTimeMillis();
    while (true) {
        try {/*w w  w . j a  va 2 s .  c  om*/
            long waitTime = System.currentTimeMillis() - startTime;
            if (timeout > 0 && waitTime > timeout) {
                throw new AmazonClientException("Timed out after " + (waitTime / 1000)
                        + " seconds of waiting for ssh to become available. (maximum timeout configured is "
                        + (timeout / 1000) + ")");
            }
            Instance instance = computer.updateInstanceDescription();
            String vpc_id = instance.getVpcId();
            String host;

            if (computer.getNode().usePrivateDnsName) {
                host = instance.getPrivateDnsName();
            } else {
                host = instance.getPublicDnsName();
                // If we fail to get a public DNS name, use the private IP.
                if (host == null || host.equals("")) {
                    host = instance.getPrivateIpAddress();
                }
            }

            if ("0.0.0.0".equals(host)) {
                logger.println("Invalid host 0.0.0.0, your host is most likely waiting for an ip address.");
                throw new IOException("goto sleep");
            }

            int port = computer.getSshPort();
            Integer slaveConnectTimeout = Integer.getInteger("jenkins.ec2.slaveConnectTimeout", 10000);
            logger.println("Connecting to " + host + " on port " + port + ", with timeout "
                    + slaveConnectTimeout + ".");
            Connection conn = new Connection(host, port);
            ProxyConfiguration proxyConfig = Jenkins.getInstance().proxy;
            Proxy proxy = proxyConfig == null ? Proxy.NO_PROXY : proxyConfig.createProxy(host);
            if (!proxy.equals(Proxy.NO_PROXY) && proxy.address() instanceof InetSocketAddress) {
                InetSocketAddress address = (InetSocketAddress) proxy.address();
                HTTPProxyData proxyData = null;
                if (null != proxyConfig.getUserName()) {
                    proxyData = new HTTPProxyData(address.getHostName(), address.getPort(),
                            proxyConfig.getUserName(), proxyConfig.getPassword());
                } else {
                    proxyData = new HTTPProxyData(address.getHostName(), address.getPort());
                }
                conn.setProxyData(proxyData);
            }
            // currently OpenSolaris offers no way of verifying the host certificate, so just accept it blindly,
            // hoping that no man-in-the-middle attack is going on.
            conn.connect(new ServerHostKeyVerifier() {
                public boolean verifyServerHostKey(String hostname, int port, String serverHostKeyAlgorithm,
                        byte[] serverHostKey) throws Exception {
                    return true;
                }
            }, slaveConnectTimeout, slaveConnectTimeout);
            logger.println("Connected via SSH.");
            return conn; // successfully connected
        } catch (IOException e) {
            // keep retrying until SSH comes up
            logger.println("Waiting for SSH to come up. Sleeping 5.");
            Thread.sleep(5000);
        }
    }
}

From source file:io.druid.common.aws.ConfigDrivenAwsCredentialsConfigProvider.java

License:Apache License

@Override
public com.amazonaws.auth.AWSCredentials getCredentials() {
    if (!Strings.isNullOrEmpty(config.getAccessKey()) && !Strings.isNullOrEmpty(config.getSecretKey())) {
        return new com.amazonaws.auth.AWSCredentials() {
            @Override/*from   w w  w  . jav a  2s  .  com*/
            public String getAWSAccessKeyId() {
                return config.getAccessKey();
            }

            @Override
            public String getAWSSecretKey() {
                return config.getSecretKey();
            }
        };
    }
    throw new AmazonClientException("Unable to load AWS credentials from druid AWSCredentialsConfig");
}

From source file:jp.co.hde.mail.ses.CMCAmazonClient.java

License:Apache License

public SendEmailResult sendEmail(SendEmailRequest req) {

    if (req == null) {
        throw new AmazonClientException("SendEmailRequest is null");
    }//w  w  w .  ja v a  2  s . c  o m

    if (this.hostname == null) {
        throw new AmazonClientException("hostname is null");
    }

    Properties props = new Properties();
    props.put("mail.smtp.host", this.hostname);

    Session session = Session.getInstance(props);
    MimeMessage message = new MimeMessage(session);

    Destination dest = req.getDestination();
    if (dest == null) {
        throw new AmazonClientException("Destination is null");
    }

    try {
        // To
        List<String> toAddrs = dest.getToAddresses();
        if (toAddrs != null && toAddrs.size() > 0) {
            message.setRecipients(RecipientType.TO, toArray(toAddrs));
        } else {
            throw new AmazonClientException("To Address is not exist");
        }

        // Cc
        List<String> ccAddrs = dest.getCcAddresses();
        if (ccAddrs != null && ccAddrs.size() > 0) {
            message.setRecipients(RecipientType.CC, toArray(ccAddrs));
        }

        // Bcc
        List<String> bccAddrs = dest.getBccAddresses();
        if (bccAddrs != null && bccAddrs.size() > 0) {
            message.setRecipients(RecipientType.BCC, toArray(bccAddrs));
        }
    } catch (AddressException e) {
        throw new AmazonClientException("Invalid internet address: " + e.getMessage());
    } catch (MessagingException e) {
        throw new AmazonClientException("setRecipients failed: " + e.getMessage());
    }

    // From
    try {
        message.setFrom(new InternetAddress(req.getSource()));
    } catch (MessagingException e) {
        throw new AmazonClientException("setFrom failed: " + e.getMessage());
    }

    // Date
    try {
        message.setSentDate(new Date());
    } catch (MessagingException e) {
        throw new AmazonClientException("setSentDate failed: " + e.getMessage());
    }

    Message original = req.getMessage();
    if (original != null) {
        // Subject
        try {
            Content subject = original.getSubject();
            if (subject != null) {
                message.setSubject(subject.getData(), subject.getCharset());
            } else {
                message.setSubject("");
            }
        } catch (MessagingException e) {
            throw new AmazonClientException("setSubject failed: " + e.getMessage());
        }

        // Body
        Body body = original.getBody();
        if (body != null) {
            try {
                Content htmlBody = body.getHtml();
                Content textBody = body.getText();
                if (htmlBody != null && textBody != null) {
                    String htmlData = htmlBody.getData();
                    if (htmlData != null && !htmlData.isEmpty()) {
                        // Create multipart message
                        Multipart multipart = new MimeMultipart("alternative");

                        // TextPart
                        MimeBodyPart textPart = new MimeBodyPart();
                        if (textBody != null) {
                            String textData = textBody.getData();
                            if (textData != null && !textData.isEmpty()) {
                                textPart.setText(textData, textBody.getCharset());
                            } else {
                                textPart.setText("");
                            }
                        }
                        // HtmlPart
                        MimeBodyPart htmlPart = new MimeBodyPart();
                        htmlPart.setText(htmlData, htmlBody.getCharset(), "html");
                        htmlPart.addHeader("Content-Transfer-Encoding", "base64");
                        // Add multipart body in the message
                        multipart.addBodyPart(textPart);
                        multipart.addBodyPart(htmlPart);
                        message.setContent(multipart);
                    }
                } else if (htmlBody != null) {
                    message.setText(htmlBody.getData(), htmlBody.getCharset(), "html");
                    if (htmlBody.getCharset() != null
                            && htmlBody.getCharset().equalsIgnoreCase("iso-2022-jp")) {
                        message.addHeader("Content-Transfer-Encoding", "7bit");
                    }
                } else if (textBody != null) {
                    message.setText(textBody.getData(), textBody.getCharset());
                    if (textBody.getCharset() != null
                            && textBody.getCharset().equalsIgnoreCase("iso-2022-jp")) {
                        message.addHeader("Content-Transfer-Encoding", "7bit");
                    }
                } else {
                    throw new AmazonClientException("Message body is not exist");
                }
            } catch (MessagingException e) {
                throw new AmazonClientException("setContent failed: " + e.getMessage());
            }
        } else {
            throw new AmazonClientException("Message body is not exist");
        }

    } else {
        throw new AmazonClientException("Message is not exist");
    }

    // Send email
    try {
        SendEmailResult result = new SendEmailResult();
        if (this.username != null) {
            if (this.password == null) {
                throw new AmazonClientException("SMTP-Auth password is not exist");
            }
            CMCTransport.send(message, this.username, this.password);
        } else {
            CMCTransport.send(message);
        }
        result.setMessageId(message.getMessageID());
        return result;
    } catch (MessagingException e) {
        throw new AmazonClientException("CMCTransport.send failed : " + e.getMessage());
    }
}

From source file:jp.primecloud.auto.aws.typica.EucaEc2Client.java

License:Open Source License

@Override
public AllocateAddressResult allocateAddress(AllocateAddressRequest allocateAddressRequest) {
    try {//  ww w  . j  a va2s.  co m
        String publicIp = jec2.allocateAddress();
        return new AllocateAddressResult().withPublicIp(publicIp);
    } catch (EC2Exception e) {
        throw new AmazonClientException(e);
    }
}

From source file:jp.primecloud.auto.aws.typica.EucaEc2Client.java

License:Open Source License

@Override
public AssociateAddressResult associateAddress(AssociateAddressRequest associateAddressRequest) {
    try {//from w  w w. jav  a2  s  .  c o  m
        jec2.associateAddress(associateAddressRequest.getInstanceId(), associateAddressRequest.getPublicIp());
        return new AssociateAddressResult();
    } catch (EC2Exception e) {
        throw new AmazonClientException(e);
    }
}

From source file:jp.primecloud.auto.aws.typica.EucaEc2Client.java

License:Open Source License

@Override
public AttachVolumeResult attachVolume(AttachVolumeRequest attachVolumeRequest) {
    try {/*from   ww  w . j a v a  2  s.  c  o  m*/
        AttachmentInfo info = jec2.attachVolume(attachVolumeRequest.getVolumeId(),
                attachVolumeRequest.getInstanceId(), attachVolumeRequest.getDevice());
        VolumeAttachment attachment = new VolumeAttachmentConverter().convert(info);
        return new AttachVolumeResult().withAttachment(attachment);
    } catch (EC2Exception e) {
        throw new AmazonClientException(e);
    }
}