private static void describeInstancesBatch()

in src/main/java/com/amazon/jenkins/ec2fleet/EC2Api.java [73:117]


    private static void describeInstancesBatch(
            final AmazonEC2 ec2, final Map<String, Instance> described, final List<String> batch) {
        // we are going to modify list, so copy
        final List<String> copy = new ArrayList<>(batch);

        // just to simplify debug by having consist order
        Collections.sort(copy);

        // because instances could be terminated at any time we do multiple
        // retry to get status and all time remove from request all non found instances if any
        while (copy.size() > 0) {
            try {
                final DescribeInstancesRequest request = new DescribeInstancesRequest().withInstanceIds(copy);

                DescribeInstancesResult result;
                do {
                    result = ec2.describeInstances(request);
                    request.setNextToken(result.getNextToken());

                    for (final Reservation r : result.getReservations()) {
                        for (final Instance instance : r.getInstances()) {
                            // if instance not in terminated state, add it to described
                            if (!TERMINATED_STATES.contains(instance.getState().getName())) {
                                described.put(instance.getInstanceId(), instance);
                            }
                        }
                    }
                } while (result.getNextToken() != null);

                // all good, clear request batch to stop
                copy.clear();
            } catch (final AmazonEC2Exception exception) {
                // if we cannot find instance, that's fine assume them as terminated
                // remove from request and try again
                if (exception.getErrorCode().equals(NOT_FOUND_ERROR_CODE)) {
                    final List<String> notFoundInstanceIds = parseInstanceIdsFromNotFoundException(exception.getMessage());
                    if (notFoundInstanceIds.isEmpty()) {
                        // looks like we cannot parse correctly, rethrow
                        throw exception;
                    }
                    copy.removeAll(notFoundInstanceIds);
                }
            }
        }
    }