List of usage examples for com.amazonaws AmazonServiceException getErrorCode
public String getErrorCode()
From source file:fsi_admin.JAwsS3Conn.java
License:Open Source License
@SuppressWarnings("rawtypes") private boolean subirArchivo(StringBuffer msj, AmazonS3 s3, String S3BUKT, String nombre, Vector archivos) { //System.out.println("AwsConn SubirArchivo:" + nombre + ":nombre"); if (!archivos.isEmpty()) { FileItem actual = null;// w ww. ja v a 2 s .com try { for (int i = 0; i < archivos.size(); i++) { InputStream inputStream = null; try { actual = (FileItem) archivos.elementAt(i); ///////////////////////////////////////////////////////// //Obtain the Content length of the Input stream for S3 header InputStream is = actual.getInputStream(); byte[] contentBytes = IOUtils.toByteArray(is); Long contentLength = Long.valueOf(contentBytes.length); ObjectMetadata metadata = new ObjectMetadata(); metadata.setContentLength(contentLength); //Reobtain the tmp uploaded file as input stream inputStream = actual.getInputStream(); //Put the object in S3 //System.out.println("BUCKET: " + S3BUKT + " OBJETO: " + nombre.replace('_', '-')); //System.out.println("BUCKET: " + S3BUKT + " OBJETO: " + nombre.replace('_', '-')); s3.putObject(new PutObjectRequest(S3BUKT, nombre, inputStream, metadata)); } finally { if (inputStream != null) try { inputStream.close(); } catch (IOException e) { e.printStackTrace(); } } //////////////////////////////////////////////////////////// } return true; } catch (AmazonServiceException ase) { ase.printStackTrace(); msj.append("Error de AmazonServiceException al subir archivo a S3.<br>"); msj.append("Mensaje: " + ase.getMessage() + "<br>"); msj.append("Cdigo de Estatus HTTP: " + ase.getStatusCode() + "<br>"); msj.append("Cdigo de Error AWS: " + ase.getErrorCode() + "<br>"); msj.append("Tipo de Error: " + ase.getErrorType() + "<br>"); msj.append("Request ID: " + ase.getRequestId()); return false; } catch (AmazonClientException ace) { ace.printStackTrace(); msj.append("Error de AmazonClientException al subir archivo a S3.<br>"); msj.append("Mensaje: " + ace.getMessage()); return false; } catch (IOException e) { e.printStackTrace(); msj.append("Error de Entrada/Salida al subir archivo a S3: " + e.getMessage()); return false; } } else { msj.append("Error al subir archivo a la nube: No se envi ningun archivo"); return false; } }
From source file:fsi_admin.JAwsS3Conn.java
License:Open Source License
private boolean eliminarArchivo(StringBuffer msj, AmazonS3 s3, String S3BUKT, String nombre) { //System.out.println("AwsConn EliminarArchivo:" + nombre + ":nombre"); try {/*from w w w . j av a 2 s . c o m*/ //System.out.println("BUCKET: " + S3BUKT + " OBJETO: " + nombre.replace('_', '-')); //System.out.println("BUCKET: " + S3BUKT + " OBJETO: " + nombre.replace('_', '-')); s3.deleteObject(S3BUKT, nombre); return true; } catch (AmazonServiceException ase) { ase.printStackTrace(); msj.append("Error de AmazonServiceException al eliminar archivo de S3.<br>"); msj.append("Mensaje: " + ase.getMessage() + "<br>"); msj.append("Cdigo de Estatus HTTP: " + ase.getStatusCode() + "<br>"); msj.append("Cdigo de Error AWS: " + ase.getErrorCode() + "<br>"); msj.append("Tipo de Error: " + ase.getErrorType() + "<br>"); msj.append("Request ID: " + ase.getRequestId()); return false; } catch (AmazonClientException ace) { ace.printStackTrace(); msj.append("Error de AmazonClientException al eliminar archivo de S3.<br>"); msj.append("Mensaje: " + ace.getMessage()); return false; } }
From source file:fsi_admin.JAwsS3Conn.java
License:Open Source License
private boolean descargarArchivo(HttpServletResponse response, StringBuffer msj, AmazonS3 s3, String S3BUKT, String nombre, String destino) { //System.out.println("AwsConn DescargarArchivo:" + nombre + ":nombre"); try {/*from w ww . ja v a2 s . com*/ System.out.println("DESCARGA BUCKET: " + S3BUKT + " OBJETO: " + nombre); S3Object object = s3.getObject(new GetObjectRequest(S3BUKT, nombre)); //out.println("Content-Type: " + object.getObjectMetadata().getContentType()); //System.out.println("Content-Type: " + object.getObjectMetadata().getContentType()); byte[] byteArray = IOUtils.toByteArray(object.getObjectContent()); ByteArrayInputStream bais = new ByteArrayInputStream(byteArray); JBajarArchivo fd = new JBajarArchivo(); fd.doDownload(response, getServletConfig().getServletContext(), bais, object.getObjectMetadata().getContentType(), byteArray.length, destino); System.out.println("Content-Length: " + object.getObjectMetadata().getContentLength() + " BA: " + byteArray.length); return true; } catch (AmazonServiceException ase) { ase.printStackTrace(); msj.append("Error de AmazonServiceException al descargar archivo de S3.<br>"); msj.append("Mensaje: " + ase.getMessage() + "<br>"); msj.append("Cdigo de Estatus HTTP: " + ase.getStatusCode() + "<br>"); msj.append("Cdigo de Error AWS: " + ase.getErrorCode() + "<br>"); msj.append("Tipo de Error: " + ase.getErrorType() + "<br>"); msj.append("Request ID: " + ase.getRequestId()); return false; } catch (AmazonClientException ace) { ace.printStackTrace(); msj.append("Error de AmazonClientException al descargar archivo de S3.<br>"); msj.append("Mensaje: " + ace.getMessage()); return false; } catch (IOException ace) { ace.printStackTrace(); msj.append("Error de IOException al descargar archivo de S3.<br>"); msj.append("Mensaje: " + ace.getMessage()); return false; } }
From source file:getting_started.GettingStartedApp.java
License:Open Source License
public static void main(String[] args) throws Exception { System.out.println("==========================================="); System.out.println("Welcome to the AWS Java SDK!"); System.out.println("==========================================="); /*/*from w w w. j av a 2s. c o m*/ * Amazon EC2 * * The AWS EC2 client allows you to create, delete, and administer * instances programmatically. * * In this sample, we use an EC2 client to submit a Spot request, * wait for it to reach the active state, and then cancel and terminate * the associated instance. */ try { // Setup the helper object that will perform all of the API calls. Requests requests = new Requests(); // Submit all of the requests. requests.submitRequests(); // Loop through all of the requests until all bids are in the active state // (or at least not in the open state). do { // Sleep for 60 seconds. Thread.sleep(SLEEP_CYCLE); } while (requests.areAnyOpen()); // Cancel all requests and terminate all running instances. requests.cleanup(); } catch (AmazonServiceException ase) { // Write out any exceptions that may have occurred. 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:getting_started.InlineGettingStartedCodeSampleApp.java
License:Open Source License
/** * @param args// www . j ava2 s .co m */ public static void main(String[] args) { //============================================================================================// //=============================== Submitting a Request =======================================// //============================================================================================// // Retrieves the credentials from an AWSCredentials.properties file. AWSCredentials credentials = null; try { credentials = new PropertiesCredentials( InlineGettingStartedCodeSampleApp.class.getResourceAsStream("AwsCredentials.properties")); } catch (IOException e1) { System.out.println("Credentials were not properly entered into AwsCredentials.properties."); System.out.println(e1.getMessage()); System.exit(-1); } // Create the AmazonEC2Client object so we can call various APIs. AmazonEC2 ec2 = new AmazonEC2Client(credentials); // Initializes a Spot Instance Request RequestSpotInstancesRequest requestRequest = new RequestSpotInstancesRequest(); // Request 1 x t1.micro instance with a bid price of $0.03. requestRequest.setSpotPrice("0.03"); requestRequest.setInstanceCount(Integer.valueOf(1)); // Setup the specifications of the launch. This includes the instance type (e.g. t1.micro) // and the latest Amazon Linux AMI id available. Note, you should always use the latest // Amazon Linux AMI id or another of your choosing. LaunchSpecification launchSpecification = new LaunchSpecification(); launchSpecification.setImageId("ami-8c1fece5"); launchSpecification.setInstanceType("t1.micro"); // Add the security group to the request. ArrayList<String> securityGroups = new ArrayList<String>(); securityGroups.add("GettingStartedGroup"); launchSpecification.setSecurityGroups(securityGroups); // Add the launch specifications to the request. requestRequest.setLaunchSpecification(launchSpecification); //============================================================================================// //=========================== Getting the Request ID from the Request ========================// //============================================================================================// // Call the RequestSpotInstance API. RequestSpotInstancesResult requestResult = ec2.requestSpotInstances(requestRequest); List<SpotInstanceRequest> requestResponses = requestResult.getSpotInstanceRequests(); // Setup an arraylist to collect all of the request ids we want to watch hit the running // state. ArrayList<String> spotInstanceRequestIds = new ArrayList<String>(); // Add all of the request ids to the hashset, so we can determine when they hit the // active state. for (SpotInstanceRequest requestResponse : requestResponses) { System.out.println("Created Spot Request: " + requestResponse.getSpotInstanceRequestId()); spotInstanceRequestIds.add(requestResponse.getSpotInstanceRequestId()); } //============================================================================================// //=========================== Determining the State of the Spot Request ======================// //============================================================================================// // Create a variable that will track whether there are any requests still in the open state. boolean anyOpen; // Initialize variables. ArrayList<String> instanceIds = new ArrayList<String>(); do { // Create the describeRequest with tall of the request id to monitor (e.g. that we started). DescribeSpotInstanceRequestsRequest describeRequest = new DescribeSpotInstanceRequestsRequest(); describeRequest.setSpotInstanceRequestIds(spotInstanceRequestIds); // Initialize the anyOpen variable to false which assumes there are no requests open unless // we find one that is still open. anyOpen = false; try { // Retrieve all of the requests we want to monitor. DescribeSpotInstanceRequestsResult describeResult = ec2 .describeSpotInstanceRequests(describeRequest); List<SpotInstanceRequest> describeResponses = describeResult.getSpotInstanceRequests(); // Look through each request and determine if they are all in the active state. for (SpotInstanceRequest describeResponse : describeResponses) { // If the state is open, it hasn't changed since we attempted to request it. // There is the potential for it to transition almost immediately to closed or // cancelled so we compare against open instead of active. if (describeResponse.getState().equals("open")) { anyOpen = true; break; } // Add the instance id to the list we will eventually terminate. instanceIds.add(describeResponse.getInstanceId()); } } catch (AmazonServiceException e) { // If we have an exception, ensure we don't break out of the loop. // This prevents the scenario where there was blip on the wire. anyOpen = true; } try { // Sleep for 60 seconds. Thread.sleep(60 * 1000); } catch (Exception e) { // Do nothing because it woke up early. } } while (anyOpen); //============================================================================================// //====================================== Canceling the Request ==============================// //============================================================================================// try { // Cancel requests. CancelSpotInstanceRequestsRequest cancelRequest = new CancelSpotInstanceRequestsRequest( spotInstanceRequestIds); ec2.cancelSpotInstanceRequests(cancelRequest); } catch (AmazonServiceException e) { // Write out any exceptions that may have occurred. System.out.println("Error cancelling instances"); System.out.println("Caught Exception: " + e.getMessage()); System.out.println("Reponse Status Code: " + e.getStatusCode()); System.out.println("Error Code: " + e.getErrorCode()); System.out.println("Request ID: " + e.getRequestId()); } //============================================================================================// //=================================== Terminating any Instances ==============================// //============================================================================================// try { // Terminate instances. TerminateInstancesRequest terminateRequest = new TerminateInstancesRequest(instanceIds); ec2.terminateInstances(terminateRequest); } catch (AmazonServiceException e) { // Write out any exceptions that may have occurred. System.out.println("Error terminating instances"); System.out.println("Caught Exception: " + e.getMessage()); System.out.println("Reponse Status Code: " + e.getStatusCode()); System.out.println("Error Code: " + e.getErrorCode()); System.out.println("Request ID: " + e.getRequestId()); } }
From source file:getting_started.SimpleQueueServiceSample.java
License:Open Source License
public static void main(String[] args) throws Exception { /*// w w w .ja v a 2 s . c o m * Important: Be sure to fill in your AWS access credentials in the * AwsCredentials.properties file before you try to run this * sample. * http://aws.amazon.com/security-credentials */ AmazonSQS sqs = new AmazonSQSClient(new PropertiesCredentials( SimpleQueueServiceSample.class.getResourceAsStream("AwsCredentials.properties"))); System.out.println("==========================================="); System.out.println("Getting Started with Amazon SQS"); System.out.println("===========================================\n"); try { // Create a queue System.out.println("Creating a new SQS queue called MyQueue.\n"); CreateQueueRequest createQueueRequest = new CreateQueueRequest("MyQueue"); String myQueueUrl = sqs.createQueue(createQueueRequest).getQueueUrl(); // List queues System.out.println("Listing all queues in your account.\n"); for (String queueUrl : sqs.listQueues().getQueueUrls()) { System.out.println(" QueueUrl: " + queueUrl); } System.out.println(); // Send a message System.out.println("Sending a message to MyQueue.\n"); sqs.sendMessage(new SendMessageRequest(myQueueUrl, "This is my message text.")); // Receive messages System.out.println("Receiving messages from MyQueue.\n"); ReceiveMessageRequest receiveMessageRequest = new ReceiveMessageRequest(myQueueUrl); List<Message> messages = sqs.receiveMessage(receiveMessageRequest).getMessages(); for (Message message : messages) { System.out.println(" Message"); System.out.println(" MessageId: " + message.getMessageId()); System.out.println(" ReceiptHandle: " + message.getReceiptHandle()); System.out.println(" MD5OfBody: " + message.getMD5OfBody()); System.out.println(" Body: " + message.getBody()); for (Entry<String, String> entry : message.getAttributes().entrySet()) { System.out.println(" Attribute"); System.out.println(" Name: " + entry.getKey()); System.out.println(" Value: " + entry.getValue()); } } System.out.println(); // Delete a message System.out.println("Deleting a message.\n"); String messageRecieptHandle = messages.get(0).getReceiptHandle(); sqs.deleteMessage(new DeleteMessageRequest(myQueueUrl, messageRecieptHandle)); // Delete a queue System.out.println("Deleting the test queue.\n"); sqs.deleteQueue(new DeleteQueueRequest(myQueueUrl)); } catch (AmazonServiceException ase) { System.out.println("Caught an AmazonServiceException, which means your request made it " + "to Amazon SQS, but was rejected with an error response for some reason."); System.out.println("Error Message: " + ase.getMessage()); System.out.println("HTTP Status Code: " + ase.getStatusCode()); System.out.println("AWS Error Code: " + ase.getErrorCode()); System.out.println("Error Type: " + ase.getErrorType()); System.out.println("Request ID: " + ase.getRequestId()); } catch (AmazonClientException ace) { System.out.println("Caught an AmazonClientException, which means the client encountered " + "a serious internal problem while trying to communicate with SQS, such as not " + "being able to access the network."); System.out.println("Error Message: " + ace.getMessage()); } }
From source file:hu.cloud.edu.SimpleQueueServiceSample.java
License:Open Source License
public static void main(String[] args) throws Exception { /*/*w w w . ja v a 2s.c o m*/ * The ProfileCredentialsProvider will return your [default] * credential profile by reading from the credentials file located at * (C:\\Users\\Isaac\\.aws\\credentials). */ AWSCredentials credentials = null; try { credentials = new ProfileCredentialsProvider("default").getCredentials(); } catch (Exception e) { throw new AmazonClientException("Cannot load the credentials from the credential profiles file. " + "Please make sure that your credentials file is at the correct " + "location (C:\\Users\\Isaac\\.aws\\credentials), and is in valid format.", e); } AmazonSQS sqs = new AmazonSQSClient(credentials); Region usWest2 = Region.getRegion(Regions.US_WEST_2); sqs.setRegion(usWest2); System.out.println("==========================================="); System.out.println("Getting Started with Amazon SQS"); System.out.println("===========================================\n"); try { // Create a queue System.out.println("Creating a new SQS queue called MyQueue.\n"); CreateQueueRequest createQueueRequest = new CreateQueueRequest("MyQueue"); String myQueueUrl = sqs.createQueue(createQueueRequest).getQueueUrl(); // List queues System.out.println("Listing all queues in your account.\n"); for (String queueUrl : sqs.listQueues().getQueueUrls()) { System.out.println(" QueueUrl: " + queueUrl); } System.out.println(); // Send a message System.out.println("Sending a message to MyQueue.\n"); sqs.sendMessage(new SendMessageRequest(myQueueUrl, "This is my message text.")); // Receive messages System.out.println("Receiving messages from MyQueue.\n"); ReceiveMessageRequest receiveMessageRequest = new ReceiveMessageRequest(myQueueUrl); List<Message> messages = sqs.receiveMessage(receiveMessageRequest).getMessages(); for (Message message : messages) { System.out.println(" Message"); System.out.println(" MessageId: " + message.getMessageId()); System.out.println(" ReceiptHandle: " + message.getReceiptHandle()); System.out.println(" MD5OfBody: " + message.getMD5OfBody()); System.out.println(" Body: " + message.getBody()); for (Entry<String, String> entry : message.getAttributes().entrySet()) { System.out.println(" Attribute"); System.out.println(" Name: " + entry.getKey()); System.out.println(" Value: " + entry.getValue()); } } System.out.println(); // Delete a message System.out.println("Deleting a message.\n"); String messageRecieptHandle = messages.get(0).getReceiptHandle(); sqs.deleteMessage(new DeleteMessageRequest(myQueueUrl, messageRecieptHandle)); // Delete a queue System.out.println("Deleting the test queue.\n"); sqs.deleteQueue(new DeleteQueueRequest(myQueueUrl)); } catch (AmazonServiceException ase) { System.out.println("Caught an AmazonServiceException, which means your request made it " + "to Amazon SQS, but was rejected with an error response for some reason."); System.out.println("Error Message: " + ase.getMessage()); System.out.println("HTTP Status Code: " + ase.getStatusCode()); System.out.println("AWS Error Code: " + ase.getErrorCode()); System.out.println("Error Type: " + ase.getErrorType()); System.out.println("Request ID: " + ase.getRequestId()); } catch (AmazonClientException ace) { System.out.println("Caught an AmazonClientException, which means the client encountered " + "a serious internal problem while trying to communicate with SQS, such as not " + "being able to access the network."); System.out.println("Error Message: " + ace.getMessage()); } }
From source file:hudson.plugins.ec2.EC2Computer.java
License:Open Source License
private Instance _describeInstance() throws AmazonClientException, InterruptedException { // Sometimes even after a successful RunInstances, DescribeInstances // returns an error for a few seconds. We do a few retries instead of // failing instantly. See [JENKINS-15319]. for (int i = 0; i < 5; i++) { try {//from ww w . j a v a 2 s .c om return _describeInstanceOnce(); } catch (AmazonServiceException e) { if (e.getErrorCode().equals("InvalidInstanceID.NotFound")) { // retry in 5 seconds. Thread.sleep(5000); continue; } throw e; } } // Last time, throw on any error. return _describeInstanceOnce(); }
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. *//* ww w .jav 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:hudson.plugins.ec2.SlaveTemplate.java
License:Open Source License
/** * Provision a new slave for an EC2 spot instance to call back to Jenkins *//*from w w w.j a v a2 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); } }