Search in sources :

Example 1 with ElasticSearchException

use of org.elasticsearch.ElasticSearchException in project elasticsearch by elastic.

the class ShardGetService method innerGetLoadFromStoredFields.

private GetResult innerGetLoadFromStoredFields(String type, String id, String[] gFields, FetchSourceContext fetchSourceContext, Engine.GetResult get, MapperService mapperService) {
    Map<String, GetField> fields = null;
    BytesReference source = null;
    Versions.DocIdAndVersion docIdAndVersion = get.docIdAndVersion();
    FieldsVisitor fieldVisitor = buildFieldsVisitors(gFields, fetchSourceContext);
    if (fieldVisitor != null) {
        try {
            docIdAndVersion.context.reader().document(docIdAndVersion.docId, fieldVisitor);
        } catch (IOException e) {
            throw new ElasticsearchException("Failed to get type [" + type + "] and id [" + id + "]", e);
        }
        source = fieldVisitor.source();
        if (!fieldVisitor.fields().isEmpty()) {
            fieldVisitor.postProcess(mapperService);
            fields = new HashMap<>(fieldVisitor.fields().size());
            for (Map.Entry<String, List<Object>> entry : fieldVisitor.fields().entrySet()) {
                fields.put(entry.getKey(), new GetField(entry.getKey(), entry.getValue()));
            }
        }
    }
    DocumentMapper docMapper = mapperService.documentMapper(type);
    if (docMapper.parentFieldMapper().active()) {
        String parentId = ParentFieldSubFetchPhase.getParentId(docMapper.parentFieldMapper(), docIdAndVersion.context.reader(), docIdAndVersion.docId);
        if (fields == null) {
            fields = new HashMap<>(1);
        }
        fields.put(ParentFieldMapper.NAME, new GetField(ParentFieldMapper.NAME, Collections.singletonList(parentId)));
    }
    if (gFields != null && gFields.length > 0) {
        for (String field : gFields) {
            FieldMapper fieldMapper = docMapper.mappers().smartNameFieldMapper(field);
            if (fieldMapper == null) {
                if (docMapper.objectMappers().get(field) != null) {
                    // Only fail if we know it is a object field, missing paths / fields shouldn't fail.
                    throw new IllegalArgumentException("field [" + field + "] isn't a leaf field");
                }
            }
        }
    }
    if (!fetchSourceContext.fetchSource()) {
        source = null;
    } else if (fetchSourceContext.includes().length > 0 || fetchSourceContext.excludes().length > 0) {
        Map<String, Object> sourceAsMap;
        XContentType sourceContentType = null;
        // TODO: The source might parsed and available in the sourceLookup but that one uses unordered maps so different. Do we care?
        Tuple<XContentType, Map<String, Object>> typeMapTuple = XContentHelper.convertToMap(source, true);
        sourceContentType = typeMapTuple.v1();
        sourceAsMap = typeMapTuple.v2();
        sourceAsMap = XContentMapValues.filter(sourceAsMap, fetchSourceContext.includes(), fetchSourceContext.excludes());
        try {
            source = XContentFactory.contentBuilder(sourceContentType).map(sourceAsMap).bytes();
        } catch (IOException e) {
            throw new ElasticsearchException("Failed to get type [" + type + "] and id [" + id + "] with includes/excludes set", e);
        }
    }
    return new GetResult(shardId.getIndexName(), type, id, get.version(), get.exists(), source, fields);
}
Also used : BytesReference(org.elasticsearch.common.bytes.BytesReference) FieldsVisitor(org.elasticsearch.index.fieldvisitor.FieldsVisitor) CustomFieldsVisitor(org.elasticsearch.index.fieldvisitor.CustomFieldsVisitor) DocumentMapper(org.elasticsearch.index.mapper.DocumentMapper) IOException(java.io.IOException) ElasticsearchException(org.elasticsearch.ElasticsearchException) Versions(org.elasticsearch.common.lucene.uid.Versions) XContentType(org.elasticsearch.common.xcontent.XContentType) List(java.util.List) HashMap(java.util.HashMap) Map(java.util.Map) UidFieldMapper(org.elasticsearch.index.mapper.UidFieldMapper) FieldMapper(org.elasticsearch.index.mapper.FieldMapper) ParentFieldMapper(org.elasticsearch.index.mapper.ParentFieldMapper) SourceFieldMapper(org.elasticsearch.index.mapper.SourceFieldMapper) Tuple(org.elasticsearch.common.collect.Tuple)

Example 2 with ElasticSearchException

use of org.elasticsearch.ElasticSearchException in project elasticsearch by elastic.

the class BytesRestResponse method errorFromXContent.

public static ElasticsearchStatusException errorFromXContent(XContentParser parser) throws IOException {
    XContentParser.Token token = parser.nextToken();
    ensureExpectedToken(XContentParser.Token.START_OBJECT, token, parser::getTokenLocation);
    ElasticsearchException exception = null;
    RestStatus status = null;
    String currentFieldName = null;
    while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
        if (token == XContentParser.Token.FIELD_NAME) {
            currentFieldName = parser.currentName();
        }
        if (STATUS.equals(currentFieldName)) {
            if (token != XContentParser.Token.FIELD_NAME) {
                ensureExpectedToken(XContentParser.Token.VALUE_NUMBER, token, parser::getTokenLocation);
                status = RestStatus.fromCode(parser.intValue());
            }
        } else {
            exception = ElasticsearchException.failureFromXContent(parser);
        }
    }
    if (exception == null) {
        throw new IllegalStateException("Failed to parse elasticsearch status exception: no exception was found");
    }
    ElasticsearchStatusException result = new ElasticsearchStatusException(exception.getMessage(), status, exception.getCause());
    for (String header : exception.getHeaderKeys()) {
        result.addHeader(header, exception.getHeader(header));
    }
    for (String metadata : exception.getMetadataKeys()) {
        result.addMetadata(metadata, exception.getMetadata(metadata));
    }
    return result;
}
Also used : ElasticsearchException(org.elasticsearch.ElasticsearchException) XContentParser(org.elasticsearch.common.xcontent.XContentParser) ElasticsearchStatusException(org.elasticsearch.ElasticsearchStatusException)

Example 3 with ElasticSearchException

use of org.elasticsearch.ElasticSearchException in project elasticsearch by elastic.

the class RemoteRecoveryTargetHandler method writeFileChunk.

@Override
public void writeFileChunk(StoreFileMetaData fileMetaData, long position, BytesReference content, boolean lastChunk, int totalTranslogOps) throws IOException {
    // Pause using the rate limiter, if desired, to throttle the recovery
    final long throttleTimeInNanos;
    // always fetch the ratelimiter - it might be updated in real-time on the recovery settings
    final RateLimiter rl = recoverySettings.rateLimiter();
    if (rl != null) {
        long bytes = bytesSinceLastPause.addAndGet(content.length());
        if (bytes > rl.getMinPauseCheckBytes()) {
            // Time to pause
            bytesSinceLastPause.addAndGet(-bytes);
            try {
                throttleTimeInNanos = rl.pause(bytes);
                onSourceThrottle.accept(throttleTimeInNanos);
            } catch (IOException e) {
                throw new ElasticsearchException("failed to pause recovery", e);
            }
        } else {
            throttleTimeInNanos = 0;
        }
    } else {
        throttleTimeInNanos = 0;
    }
    transportService.submitRequest(targetNode, PeerRecoveryTargetService.Actions.FILE_CHUNK, new RecoveryFileChunkRequest(recoveryId, shardId, fileMetaData, position, content, lastChunk, totalTranslogOps, /* we send totalOperations with every request since we collect stats on the target and that way we can
                                 * see how many translog ops we accumulate while copying files across the network. A future optimization
                                 * would be in to restart file copy again (new deltas) if we have too many translog ops are piling up.
                                 */
    throttleTimeInNanos), fileChunkRequestOptions, EmptyTransportResponseHandler.INSTANCE_SAME).txGet();
}
Also used : IOException(java.io.IOException) ElasticsearchException(org.elasticsearch.ElasticsearchException) RateLimiter(org.apache.lucene.store.RateLimiter)

Example 4 with ElasticSearchException

use of org.elasticsearch.ElasticSearchException in project elasticsearch by elastic.

the class RestController method dispatchBadRequest.

@Override
public void dispatchBadRequest(final RestRequest request, final RestChannel channel, final ThreadContext threadContext, final Throwable cause) {
    try {
        final Exception e;
        if (cause == null) {
            e = new ElasticsearchException("unknown cause");
        } else if (cause instanceof Exception) {
            e = (Exception) cause;
        } else {
            e = new ElasticsearchException(cause);
        }
        channel.sendResponse(new BytesRestResponse(channel, BAD_REQUEST, e));
    } catch (final IOException e) {
        if (cause != null) {
            e.addSuppressed(cause);
        }
        logger.warn("failed to send bad request response", e);
        channel.sendResponse(new BytesRestResponse(INTERNAL_SERVER_ERROR, BytesRestResponse.TEXT_CONTENT_TYPE, BytesArray.EMPTY));
    }
}
Also used : ElasticsearchException(org.elasticsearch.ElasticsearchException) IOException(java.io.IOException) ElasticsearchException(org.elasticsearch.ElasticsearchException) IOException(java.io.IOException)

Example 5 with ElasticSearchException

use of org.elasticsearch.ElasticSearchException in project elasticsearch by elastic.

the class IndexFieldTerm method setReader.

// when the reader changes, we have to get the posting list for this term
// and reader
private void setReader(LeafReader reader) {
    try {
        postings = getPostings(convertToLuceneFlags(flags), reader);
        if (postings == null) {
            // no term or field for this segment, fake out the postings...
            final DocIdSetIterator empty = DocIdSetIterator.empty();
            postings = new PostingsEnum() {

                @Override
                public int docID() {
                    return empty.docID();
                }

                @Override
                public int nextDoc() throws IOException {
                    return empty.nextDoc();
                }

                @Override
                public int advance(int target) throws IOException {
                    return empty.advance(target);
                }

                @Override
                public long cost() {
                    return empty.cost();
                }

                @Override
                public int freq() throws IOException {
                    return 1;
                }

                @Override
                public int nextPosition() throws IOException {
                    return -1;
                }

                @Override
                public int startOffset() throws IOException {
                    return -1;
                }

                @Override
                public int endOffset() throws IOException {
                    return -1;
                }

                @Override
                public BytesRef getPayload() throws IOException {
                    return null;
                }
            };
        }
    } catch (IOException e) {
        throw new ElasticsearchException("Unable to get postings for field " + fieldName + " and term " + term, e);
    }
}
Also used : IOException(java.io.IOException) ElasticsearchException(org.elasticsearch.ElasticsearchException) PostingsEnum(org.apache.lucene.index.PostingsEnum) FilterPostingsEnum(org.apache.lucene.index.FilterLeafReader.FilterPostingsEnum) DocIdSetIterator(org.apache.lucene.search.DocIdSetIterator) BytesRef(org.apache.lucene.util.BytesRef)

Aggregations

ElasticsearchException (org.elasticsearch.ElasticsearchException)309 IOException (java.io.IOException)127 Settings (org.elasticsearch.common.settings.Settings)32 XContentBuilder (org.elasticsearch.common.xcontent.XContentBuilder)30 HashMap (java.util.HashMap)29 ClusterState (org.elasticsearch.cluster.ClusterState)29 ArrayList (java.util.ArrayList)28 Matchers.containsString (org.hamcrest.Matchers.containsString)25 List (java.util.List)20 Map (java.util.Map)20 AtomicReference (java.util.concurrent.atomic.AtomicReference)20 ParameterizedMessage (org.apache.logging.log4j.message.ParameterizedMessage)18 XContentParser (org.elasticsearch.common.xcontent.XContentParser)17 Path (java.nio.file.Path)16 Test (org.junit.Test)16 ActionListener (org.elasticsearch.action.ActionListener)15 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)14 Version (org.elasticsearch.Version)14 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)13 ResourceNotFoundException (org.elasticsearch.ResourceNotFoundException)13