List of usage examples for com.amazonaws AmazonServiceException getErrorMessage
public String getErrorMessage()
From source file:com.cloudera.director.aws.ec2.EC2Provider.java
License:Apache License
/** * Atomically allocates multiple regular EC2 instances with the specified identifiers based on a * single instance template. If not all the instances can be allocated, the number of instances * allocated must be at least the specified minimum or the method must fail cleanly with no * billing implications./*from w ww. j a v a2 s. co m*/ * * @param template the instance template * @param virtualInstanceIds the unique identifiers for the instances * @param minCount the minimum number of instances to allocate if not all resources can * be allocated * @return the virtual instance ids of the instances that were allocated * @throws InterruptedException if the operation is interrupted */ public Collection<String> allocateOnDemandInstances(EC2InstanceTemplate template, Collection<String> virtualInstanceIds, int minCount) throws InterruptedException { int instanceCount = virtualInstanceIds.size(); LOG.info(">> Requesting {} instances for {}", instanceCount, template); // EC2 client doesn't accept a min count of 0. Readjust the requested // value to 1 to allow submitting the request. int normalizedMinCount = (minCount == 0) ? 1 : minCount; RunInstancesResult runInstancesResult; try { runInstancesResult = client .runInstances(newRunInstancesRequest(template, virtualInstanceIds, normalizedMinCount)); } catch (AmazonServiceException e) { AWSExceptions.propagateIfUnrecoverable(e); // As documented at http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-capacity.html if ("InsufficientInstanceCapacity".equals(e.getErrorCode()) || "InstanceLimitExceeded".equals(e.getErrorCode())) { if (minCount == 0) { LOG.warn("Ignoring insufficient capacity exception due to min count being zero", e); return Collections.emptyList(); } else { // fail fast on insufficient instance capacity because we expect it will take // a fair amount of time for AWS to bring more capacity online in a zone or it will // take some time for customers to request a limit increase throw new UnrecoverableProviderException(e.getErrorMessage(), e); } } else { throw AWSExceptions.propagate(e); } } if (LOG.isInfoEnabled()) { LOG.info("<< Reservation {} with {}", runInstancesResult.getReservation().getReservationId(), summarizeReservationForLogging(runInstancesResult.getReservation())); } // Tag all the new instances so that we can easily find them later on. // Determine which do not yet have a private IP address. List<Tag> userDefinedTags = getUserDefinedTags(template); Set<String> instancesWithNoPrivateIp = Sets.newHashSet(); List<Instance> instances = runInstancesResult.getReservation().getInstances(); // Limit the number of virtual instance id's used for tagging to the // number of instances that we managed to reserve. List<String> virtualInstanceIdsAllocated = FluentIterable.from(virtualInstanceIds).limit(instances.size()) .toList(); List<String> successfulVirtualInstanceIds = Lists.newArrayList(); for (Map.Entry<String, Instance> entry : zipWith(virtualInstanceIdsAllocated, instances)) { String virtualInstanceId = entry.getKey(); Instance instance = entry.getValue(); String ec2InstanceId = instance.getInstanceId(); if (tagInstance(template, userDefinedTags, virtualInstanceId, ec2InstanceId)) { successfulVirtualInstanceIds.add(virtualInstanceId); if (instance.getPrivateIpAddress() == null) { instancesWithNoPrivateIp.add(ec2InstanceId); } else { LOG.info("<< Instance {} got IP {}", ec2InstanceId, instance.getPrivateIpAddress()); } } else { LOG.info("<< Instance {} could not be tagged.", ec2InstanceId); } } int numInstancesTagged = successfulVirtualInstanceIds.size(); if (numInstancesTagged < minCount) { LOG.error( "Number of instances tagged ({}) is less than the minimum count ({}). One or more instances may have " + "unexpectedly terminated prior to tagging.", numInstancesTagged, minCount); delete(template, successfulVirtualInstanceIds); throw new UnrecoverableProviderException( String.format(COUNT_BELOW_THRESHOLD, numInstancesTagged, minCount)); } // Wait until all of them have a private IP (it should be pretty fast) waitForPrivateIpAddresses(instancesWithNoPrivateIp); return virtualInstanceIdsAllocated; }
From source file:com.netflix.spinnaker.clouddriver.aws.lifecycle.LaunchFailureNotificationCleanupAgent.java
License:Apache License
/** * Fetch scaling activities and determine if the most recent activity was successful. * * A successful scaling activity is sufficient to indicate that a server group is no longer having launch failures. *//*w ww. j a v a 2 s.co m*/ protected boolean hasLaunchFailures(AmazonAutoScaling amazonAutoScaling, EntityTags entityTags) { EntityTags.EntityRef entityRef = entityTags.getEntityRef(); try { DescribeScalingActivitiesResult describeScalingActivitiesResult = amazonAutoScaling .describeScalingActivities(new DescribeScalingActivitiesRequest() .withAutoScalingGroupName(entityRef.getEntityId())); List<Activity> activities = describeScalingActivitiesResult.getActivities(); return !activities.isEmpty() && !activities.get(0).getStatusCode().equals(ScalingActivityStatusCode.Successful.toString()); } catch (Exception e) { AmazonServiceException amazonServiceException = amazonServiceException(e); if (amazonServiceException != null) { if (amazonServiceException.getErrorMessage().toLowerCase().contains("name not found")) { return false; } } throw e; } }
From source file:com.nike.cerberus.operation.core.UpdateStackOperation.java
License:Apache License
@Override public void run(final UpdateStackCommand command) { final String stackId = configStore.getStackId(command.getStackName()); final Class<? extends LaunchConfigParameters> parametersClass = stackParameterMap .get(command.getStackName()); final Map<String, String> parameters; if (parametersClass != null) { parameters = getUpdateLaunchConfigParameters(command.getStackName(), command, parametersClass); } else if (StackName.BASE == command.getStackName()) { parameters = getUpdatedBaseStackParameters(command); } else {/*from w ww.j a v a 2 s .c om*/ throw new IllegalArgumentException("The specified stack does not support the update stack command!"); } parameters.putAll(command.getDynamicParameters()); try { logger.info("Starting the update for {}.", command.getStackName().getName()); if (command.isOverwriteTemplate()) { cloudFormationService.updateStack(stackId, parameters, stackTemplatePathMap.get(command.getStackName()), true); } else { cloudFormationService.updateStack(stackId, parameters, true); } final StackStatus endStatus = cloudFormationService.waitForStatus(stackId, Sets.newHashSet(StackStatus.UPDATE_COMPLETE, StackStatus.UPDATE_COMPLETE_CLEANUP_IN_PROGRESS, StackStatus.UPDATE_ROLLBACK_COMPLETE)); if (endStatus == StackStatus.ROLLBACK_COMPLETE) { final String errorMessage = String.format("Unexpected end status: %s", endStatus.name()); logger.error(errorMessage); throw new UnexpectedCloudFormationStatusException(errorMessage); } logger.info("Update complete."); } catch (AmazonServiceException ase) { if (ase.getStatusCode() == 400 && StringUtils.equalsIgnoreCase(ase.getErrorMessage(), "No updates are to be performed.")) { logger.warn("CloudFormation reported no changes detected."); } else { throw ase; } } }
From source file:com.pinterest.arcee.aws.EC2HostInfoDAOImpl.java
License:Apache License
private Collection<String> handleInvalidInstanceId(AmazonServiceException ex) throws Exception { List<String> instanceIds = new ArrayList<>(); if (ex.getErrorCode().equals(INSTANCE_MALFORMED_ERROR)) { Matcher matcher = MALFORMED_INSTANCE_ID_PATTERN.matcher(ex.getErrorMessage()); while (matcher.find()) { instanceIds.add(matcher.group("id")); }//from w w w.j ava2s.c o m } else if (ex.getErrorCode().equals(INSTANCE_NOT_FOUND_ERROR)) { Matcher matcher = NON_EXISTING_INSTANCE_ID_PATTERN.matcher(ex.getErrorMessage()); while (matcher.find()) { instanceIds.remove(matcher.group(0)); } } else { LOG.error(String.format("Ignore this error (Error Type: %s Error Code: %s, Error message: %s)", ex.getErrorType().toString(), ex.getErrorCode(), ex.getErrorMessage())); } return instanceIds; }
From source file:com.xpeppers.motorvehicle.services.BikeResource.java
@GET @Path("{id}") @Produces(MediaType.APPLICATION_JSON)/*from ww w . j a va 2s.co m*/ public Response getBikes(@PathParam("id") String id) { System.out.println("GET /bikes/" + id); //Mapping resource on DynamoDB table DynamoDBMapper db_mapper = new DynamoDBMapper(client); BikeMapper bike = new BikeMapper(); try { bike = db_mapper.load(BikeMapper.class, id); //The GET method means retrieve whatever information is identified by the Request-URI. return Response.status(200).entity(bike).build(); } catch (AmazonServiceException ase) { System.out.println(ase.getErrorMessage()); return Response.status(500).entity("{\"Status\":\"Error\"}").build(); } }
From source file:com.xpeppers.motorvehicle.services.BikeResource.java
@PUT @Path("{id}") @Consumes(MediaType.APPLICATION_JSON)//from w ww. j a v a 2 s.c o m public Response putBikes(@PathParam("id") String id, String content) throws IOException { System.out.println("PUT /bikes/" + id); //Mapping resource on DynamoDB table DynamoDBMapper db_mapper = new DynamoDBMapper(client); ObjectMapper obj_mapper = new ObjectMapper(); BikeMapper bike = obj_mapper.readValue(content, BikeMapper.class); bike.setId(id); try { db_mapper.save(bike); //If a new resource is created //the origin server MUST inform the user agent via the 201 response return Response.created(context.getAbsolutePath()).build(); } catch (AmazonServiceException ase) { Logger.getLogger(ase.getErrorMessage()); return Response.status(500).build(); } }
From source file:com.xpeppers.motorvehicle.services.CarResource.java
/** * Retrieves representation of an instance of com.xpeppers.motorvehicle.services.CarResource * @return an instance of java.lang.String *///from www. j a v a 2 s . c o m @GET @Path("{id}") @Produces(MediaType.APPLICATION_JSON) public Response getCars(@PathParam("id") String id) { System.out.println("GET /cars/" + id); //Mapping resource on DynamoDB table DynamoDBMapper db_mapper = new DynamoDBMapper(client); CarMapper car = new CarMapper(); try { car = db_mapper.load(CarMapper.class, id); //The GET method means retrieve whatever information is identified by the Request-URI. return Response.status(200).entity(car).build(); } catch (AmazonServiceException ase) { System.out.println(ase.getErrorMessage()); return Response.status(500).entity("{\"Status\":\"Error\"}").build(); } }
From source file:com.xpeppers.motorvehicle.services.CarResource.java
@PUT @Path("{id}") @Consumes(MediaType.APPLICATION_JSON)/* ww w . j av a 2 s . com*/ public Response putCars(@PathParam("id") String id, String content) throws IOException { System.out.println("PUT /cars/" + id); //Mapping resource on DynamoDB table DynamoDBMapper db_mapper = new DynamoDBMapper(client); ObjectMapper obj_mapper = new ObjectMapper(); CarMapper car = obj_mapper.readValue(content, CarMapper.class); car.setId(id); try { db_mapper.save(car); //If a new resource is created //the origin server MUST inform the user agent via the 201 response return Response.created(context.getAbsolutePath()).build(); } catch (AmazonServiceException ase) { Logger.getLogger(ase.getErrorMessage()); return Response.status(500).build(); } }
From source file:it.simona.magazzinosrv.BorsaResource.java
@GET //prende l id che arriva sulla risorsa dalla chiamata http @Path("{id}") @Produces(MediaType.APPLICATION_JSON)/* w w w. j a va 2 s . c o m*/ //prendo l id dall url e lo trasformo nel paramentro di tipo stringa public Response getBorsa(@PathParam("id") Integer id) throws IOException { System.out.println("GET/borsa/" + id); //Mapping resource on DynamoDB table DynamoDBMapper db_mapper = new DynamoDBMapper(client); BorsaMapper borsa = new BorsaMapper(); try { borsa = db_mapper.load(BorsaMapper.class, id); Response.status(200).entity(borsa).build(); } catch (AmazonServiceException ase) { System.out.println(ase.getErrorMessage()); return Response.status(500).entity("{\"Status\":\"Error\"}").build(); } return null; }
From source file:jp.classmethod.aws.dynamodb.DynamoDbRepository.java
License:Open Source License
protected DataAccessException processUpdateItemException(K key, AmazonClientException e) { final String format = "unable to update entity due to %s."; if (e instanceof ConditionalCheckFailedException) { if (null == findOne(key)) { return getNotFoundException(UPDATE_FAILED_ENTITY_NOT_FOUND, e); }//from w w w. ja v a 2 s . com return new OptimisticLockingFailureException(UPDATE_FAILED_NOT_FOUND_OR_BAD_VERSION, e); } else if (e instanceof ProvisionedThroughputExceededException) { throw new QueryTimeoutException(String.format(Locale.ENGLISH, format, "throttling"), e); } else if (e instanceof AmazonServiceException) { AmazonServiceException ase = (AmazonServiceException) e; if (VALIDATION_EXCEPTION.equals(ase.getErrorCode())) { if (EXPRESSION_REFERS_TO_NON_EXTANT_ATTRIBUTE.equals(ase.getErrorMessage()) && null == findOne(key)) { // if no locking and we get a specific message, then it also means the item does not exist return getNotFoundException(UPDATE_FAILED_ENTITY_NOT_FOUND, e); } return new InvalidDataAccessResourceUsageException( String.format(Locale.ENGLISH, format, "client error"), e); } else { return new DynamoDbServiceException(String.format(Locale.ENGLISH, format, "DynamoDB service error"), ase); } } else { return new InvalidDataAccessResourceUsageException( String.format(Locale.ENGLISH, format, "client error"), e); } }