Search in sources :

Example 26 with ElasticSearchException

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

the class TransportGetFieldMappingsIndexAction method addFieldMapper.

private void addFieldMapper(String field, FieldMapper fieldMapper, MapBuilder<String, FieldMappingMetaData> fieldMappings, boolean includeDefaults) {
    if (fieldMappings.containsKey(field)) {
        return;
    }
    try {
        XContentBuilder builder = XContentFactory.contentBuilder(XContentType.JSON);
        builder.startObject();
        fieldMapper.toXContent(builder, includeDefaults ? includeDefaultsParams : ToXContent.EMPTY_PARAMS);
        builder.endObject();
        fieldMappings.put(field, new FieldMappingMetaData(fieldMapper.fieldType().name(), builder.bytes()));
    } catch (IOException e) {
        throw new ElasticsearchException("failed to serialize XContent of field [" + field + "]", e);
    }
}
Also used : FieldMappingMetaData(org.elasticsearch.action.admin.indices.mapping.get.GetFieldMappingsResponse.FieldMappingMetaData) IOException(java.io.IOException) ElasticsearchException(org.elasticsearch.ElasticsearchException) XContentBuilder(org.elasticsearch.common.xcontent.XContentBuilder)

Example 27 with ElasticSearchException

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

the class TransportShardMultiGetAction method shardOperation.

@Override
protected MultiGetShardResponse shardOperation(MultiGetShardRequest request, ShardId shardId) {
    IndexService indexService = indicesService.indexServiceSafe(shardId.getIndex());
    IndexShard indexShard = indexService.getShard(shardId.id());
    if (request.refresh() && !request.realtime()) {
        indexShard.refresh("refresh_flag_mget");
    }
    MultiGetShardResponse response = new MultiGetShardResponse();
    for (int i = 0; i < request.locations.size(); i++) {
        MultiGetRequest.Item item = request.items.get(i);
        try {
            GetResult getResult = indexShard.getService().get(item.type(), item.id(), item.storedFields(), request.realtime(), item.version(), item.versionType(), item.fetchSourceContext());
            response.add(request.locations.get(i), new GetResponse(getResult));
        } catch (Exception e) {
            if (TransportActions.isShardNotAvailableException(e)) {
                throw (ElasticsearchException) e;
            } else {
                logger.debug((Supplier<?>) () -> new ParameterizedMessage("{} failed to execute multi_get for [{}]/[{}]", shardId, item.type(), item.id()), e);
                response.add(request.locations.get(i), new MultiGetResponse.Failure(request.index(), item.type(), item.id(), e));
            }
        }
    }
    return response;
}
Also used : GetResult(org.elasticsearch.index.get.GetResult) IndexService(org.elasticsearch.index.IndexService) IndexShard(org.elasticsearch.index.shard.IndexShard) Supplier(org.apache.logging.log4j.util.Supplier) ParameterizedMessage(org.apache.logging.log4j.message.ParameterizedMessage) ElasticsearchException(org.elasticsearch.ElasticsearchException)

Example 28 with ElasticSearchException

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

the class TransportExplainAction method shardOperation.

@Override
protected ExplainResponse shardOperation(ExplainRequest request, ShardId shardId) throws IOException {
    ShardSearchLocalRequest shardSearchLocalRequest = new ShardSearchLocalRequest(shardId, new String[] { request.type() }, request.nowInMillis, request.filteringAlias());
    SearchContext context = searchService.createSearchContext(shardSearchLocalRequest, SearchService.NO_TIMEOUT, null);
    Term uidTerm = new Term(UidFieldMapper.NAME, Uid.createUidAsBytes(request.type(), request.id()));
    Engine.GetResult result = null;
    try {
        result = context.indexShard().get(new Engine.Get(false, uidTerm));
        if (!result.exists()) {
            return new ExplainResponse(shardId.getIndexName(), request.type(), request.id(), false);
        }
        context.parsedQuery(context.getQueryShardContext().toQuery(request.query()));
        context.preProcess(true);
        int topLevelDocId = result.docIdAndVersion().docId + result.docIdAndVersion().context.docBase;
        Explanation explanation = context.searcher().explain(context.query(), topLevelDocId);
        for (RescoreSearchContext ctx : context.rescore()) {
            Rescorer rescorer = ctx.rescorer();
            explanation = rescorer.explain(topLevelDocId, context, ctx, explanation);
        }
        if (request.storedFields() != null || (request.fetchSourceContext() != null && request.fetchSourceContext().fetchSource())) {
            // Advantage is that we're not opening a second searcher to retrieve the _source. Also
            // because we are working in the same searcher in engineGetResult we can be sure that a
            // doc isn't deleted between the initial get and this call.
            GetResult getResult = context.indexShard().getService().get(result, request.id(), request.type(), request.storedFields(), request.fetchSourceContext());
            return new ExplainResponse(shardId.getIndexName(), request.type(), request.id(), true, explanation, getResult);
        } else {
            return new ExplainResponse(shardId.getIndexName(), request.type(), request.id(), true, explanation);
        }
    } catch (IOException e) {
        throw new ElasticsearchException("Could not explain", e);
    } finally {
        Releasables.close(result, context);
    }
}
Also used : ShardSearchLocalRequest(org.elasticsearch.search.internal.ShardSearchLocalRequest) RescoreSearchContext(org.elasticsearch.search.rescore.RescoreSearchContext) GetResult(org.elasticsearch.index.get.GetResult) Explanation(org.apache.lucene.search.Explanation) SearchContext(org.elasticsearch.search.internal.SearchContext) RescoreSearchContext(org.elasticsearch.search.rescore.RescoreSearchContext) Rescorer(org.elasticsearch.search.rescore.Rescorer) Term(org.apache.lucene.index.Term) IOException(java.io.IOException) ElasticsearchException(org.elasticsearch.ElasticsearchException) Engine(org.elasticsearch.index.engine.Engine)

Example 29 with ElasticSearchException

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

the class ClusterStateObserver method waitForNextChange.

/**
     * Wait for the next cluster state which satisfies statePredicate
     *
     * @param listener        callback listener
     * @param statePredicate predicate to check whether cluster state changes are relevant and the callback should be called
     * @param timeOutValue    a timeout for waiting. If null the global observer timeout will be used.
     */
public void waitForNextChange(Listener listener, Predicate<ClusterState> statePredicate, @Nullable TimeValue timeOutValue) {
    listener = new ContextPreservingListener(listener, contextHolder.newRestorableContext(false));
    if (observingContext.get() != null) {
        throw new ElasticsearchException("already waiting for a cluster state change");
    }
    Long timeoutTimeLeftMS;
    if (timeOutValue == null) {
        timeOutValue = this.timeOutValue;
        if (timeOutValue != null) {
            long timeSinceStartMS = TimeValue.nsecToMSec(System.nanoTime() - startTimeNS);
            timeoutTimeLeftMS = timeOutValue.millis() - timeSinceStartMS;
            if (timeoutTimeLeftMS <= 0L) {
                // things have timeout while we were busy -> notify
                logger.trace("observer timed out. notifying listener. timeout setting [{}], time since start [{}]", timeOutValue, new TimeValue(timeSinceStartMS));
                // update to latest, in case people want to retry
                timedOut = true;
                lastObservedState.set(new StoredState(clusterService.state()));
                listener.onTimeout(timeOutValue);
                return;
            }
        } else {
            timeoutTimeLeftMS = null;
        }
    } else {
        this.startTimeNS = System.nanoTime();
        this.timeOutValue = timeOutValue;
        timeoutTimeLeftMS = timeOutValue.millis();
        timedOut = false;
    }
    // sample a new state. This state maybe *older* than the supplied state if we are called from an applier,
    // which wants to wait for something else to happen
    ClusterState newState = clusterService.state();
    if (lastObservedState.get().isOlderOrDifferentMaster(newState) && statePredicate.test(newState)) {
        // good enough, let's go.
        logger.trace("observer: sampled state accepted by predicate ({})", newState);
        lastObservedState.set(new StoredState(newState));
        listener.onNewClusterState(newState);
    } else {
        logger.trace("observer: sampled state rejected by predicate ({}). adding listener to ClusterService", newState);
        final ObservingContext context = new ObservingContext(listener, statePredicate);
        if (!observingContext.compareAndSet(null, context)) {
            throw new ElasticsearchException("already waiting for a cluster state change");
        }
        clusterService.addTimeoutListener(timeoutTimeLeftMS == null ? null : new TimeValue(timeoutTimeLeftMS), clusterStateListener);
    }
}
Also used : ElasticsearchException(org.elasticsearch.ElasticsearchException) TimeValue(org.elasticsearch.common.unit.TimeValue)

Example 30 with ElasticSearchException

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

the class Bootstrap method setup.

private void setup(boolean addShutdownHook, Environment environment) throws BootstrapException {
    Settings settings = environment.settings();
    try {
        spawner.spawnNativePluginControllers(environment);
        Runtime.getRuntime().addShutdownHook(new Thread() {

            @Override
            public void run() {
                try {
                    spawner.close();
                } catch (IOException e) {
                    throw new ElasticsearchException("Failed to destroy spawned controllers", e);
                }
            }
        });
    } catch (IOException e) {
        throw new BootstrapException(e);
    }
    initializeNatives(environment.tmpFile(), BootstrapSettings.MEMORY_LOCK_SETTING.get(settings), BootstrapSettings.SYSTEM_CALL_FILTER_SETTING.get(settings), BootstrapSettings.CTRLHANDLER_SETTING.get(settings));
    // initialize probes before the security manager is installed
    initializeProbes();
    if (addShutdownHook) {
        Runtime.getRuntime().addShutdownHook(new Thread() {

            @Override
            public void run() {
                try {
                    IOUtils.close(node);
                    LoggerContext context = (LoggerContext) LogManager.getContext(false);
                    Configurator.shutdown(context);
                } catch (IOException ex) {
                    throw new ElasticsearchException("failed to stop node", ex);
                }
            }
        });
    }
    try {
        // look for jar hell
        JarHell.checkJarHell();
    } catch (IOException | URISyntaxException e) {
        throw new BootstrapException(e);
    }
    // Log ifconfig output before SecurityManager is installed
    IfConfig.logIfNecessary();
    // install SM after natives, shutdown hooks, etc.
    try {
        Security.configure(environment, BootstrapSettings.SECURITY_FILTER_BAD_DEFAULTS_SETTING.get(settings));
    } catch (IOException | NoSuchAlgorithmException e) {
        throw new BootstrapException(e);
    }
    node = new Node(environment) {

        @Override
        protected void validateNodeBeforeAcceptingRequests(final Settings settings, final BoundTransportAddress boundTransportAddress, List<BootstrapCheck> checks) throws NodeValidationException {
            BootstrapChecks.check(settings, boundTransportAddress, checks);
        }
    };
}
Also used : Node(org.elasticsearch.node.Node) IOException(java.io.IOException) ElasticsearchException(org.elasticsearch.ElasticsearchException) URISyntaxException(java.net.URISyntaxException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) LoggerContext(org.apache.logging.log4j.core.LoggerContext) NodeValidationException(org.elasticsearch.node.NodeValidationException) BoundTransportAddress(org.elasticsearch.common.transport.BoundTransportAddress) Settings(org.elasticsearch.common.settings.Settings) SecureSettings(org.elasticsearch.common.settings.SecureSettings)

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