summaryrefslogtreecommitdiff
path: root/core/src/main/java/org/elasticsearch/action/search/type/TransportSearchTypeAction.java
blob: 042534a2e7beaf662683122be830ba79d417dc71 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
/*
 * Licensed to Elasticsearch under one or more contributor
 * license agreements. See the NOTICE file distributed with
 * this work for additional information regarding copyright
 * ownership. Elasticsearch licenses this file to you under
 * the Apache License, Version 2.0 (the "License"); you may
 * not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

package org.elasticsearch.action.search.type;

import com.carrotsearch.hppc.IntArrayList;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocs;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.NoShardAvailableActionException;
import org.elasticsearch.action.search.ReduceSearchPhaseException;
import org.elasticsearch.action.search.SearchAction;
import org.elasticsearch.action.search.SearchPhaseExecutionException;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.search.ShardSearchFailure;
import org.elasticsearch.action.support.ActionFilters;
import org.elasticsearch.action.support.TransportAction;
import org.elasticsearch.action.support.TransportActions;
import org.elasticsearch.cluster.ClusterService;
import org.elasticsearch.cluster.ClusterState;
import org.elasticsearch.cluster.block.ClusterBlockLevel;
import org.elasticsearch.cluster.metadata.IndexNameExpressionResolver;
import org.elasticsearch.cluster.node.DiscoveryNode;
import org.elasticsearch.cluster.node.DiscoveryNodes;
import org.elasticsearch.cluster.routing.GroupShardsIterator;
import org.elasticsearch.cluster.routing.ShardIterator;
import org.elasticsearch.cluster.routing.ShardRouting;
import org.elasticsearch.common.Nullable;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.util.concurrent.AtomicArray;
import org.elasticsearch.search.SearchPhaseResult;
import org.elasticsearch.search.SearchShardTarget;
import org.elasticsearch.search.action.SearchServiceTransportAction;
import org.elasticsearch.search.controller.SearchPhaseController;
import org.elasticsearch.search.fetch.ShardFetchSearchRequest;
import org.elasticsearch.search.internal.InternalSearchResponse;
import org.elasticsearch.search.internal.ShardSearchTransportRequest;
import org.elasticsearch.search.query.QuerySearchResult;
import org.elasticsearch.search.query.QuerySearchResultProvider;
import org.elasticsearch.tasks.TaskManager;
import org.elasticsearch.threadpool.ThreadPool;
import org.elasticsearch.transport.TransportService;

import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;

import static org.elasticsearch.action.search.type.TransportSearchHelper.internalSearchRequest;

/**
 *
 */
public abstract class TransportSearchTypeAction extends TransportAction<SearchRequest, SearchResponse> {

    protected final ClusterService clusterService;

    protected final SearchServiceTransportAction searchService;

    protected final SearchPhaseController searchPhaseController;

    public TransportSearchTypeAction(Settings settings, ThreadPool threadPool, ClusterService clusterService,
                                     SearchServiceTransportAction searchService, SearchPhaseController searchPhaseController,
                                     ActionFilters actionFilters, IndexNameExpressionResolver indexNameExpressionResolver) {
        super(settings, SearchAction.NAME, threadPool, actionFilters, indexNameExpressionResolver, clusterService.getTaskManager());
        this.clusterService = clusterService;
        this.searchService = searchService;
        this.searchPhaseController = searchPhaseController;
    }

    protected abstract class BaseAsyncAction<FirstResult extends SearchPhaseResult> extends AbstractAsyncAction {

        protected final ActionListener<SearchResponse> listener;

        protected final GroupShardsIterator shardsIts;

        protected final SearchRequest request;

        protected final ClusterState clusterState;
        protected final DiscoveryNodes nodes;

        protected final int expectedSuccessfulOps;
        private final int expectedTotalOps;

        protected final AtomicInteger successfulOps = new AtomicInteger();
        private final AtomicInteger totalOps = new AtomicInteger();

        protected final AtomicArray<FirstResult> firstResults;
        private volatile AtomicArray<ShardSearchFailure> shardFailures;
        private final Object shardFailuresMutex = new Object();
        protected volatile ScoreDoc[] sortedShardList;

        protected BaseAsyncAction(SearchRequest request, ActionListener<SearchResponse> listener) {
            this.request = request;
            this.listener = listener;

            this.clusterState = clusterService.state();
            nodes = clusterState.nodes();

            clusterState.blocks().globalBlockedRaiseException(ClusterBlockLevel.READ);

            // TODO: I think startTime() should become part of ActionRequest and that should be used both for index name
            // date math expressions and $now in scripts. This way all apis will deal with now in the same way instead
            // of just for the _search api
            String[] concreteIndices = indexNameExpressionResolver.concreteIndices(clusterState, request.indicesOptions(), startTime(), request.indices());

            for (String index : concreteIndices) {
                clusterState.blocks().indexBlockedRaiseException(ClusterBlockLevel.READ, index);
            }

            Map<String, Set<String>> routingMap = indexNameExpressionResolver.resolveSearchRouting(clusterState, request.routing(), request.indices());

            shardsIts = clusterService.operationRouting().searchShards(clusterState, concreteIndices, routingMap, request.preference());
            expectedSuccessfulOps = shardsIts.size();
            // we need to add 1 for non active partition, since we count it in the total!
            expectedTotalOps = shardsIts.totalSizeWith1ForEmpty();

            firstResults = new AtomicArray<>(shardsIts.size());
        }

        public void start() {
            if (expectedSuccessfulOps == 0) {
                // no search shards to search on, bail with empty response (it happens with search across _all with no indices around and consistent with broadcast operations)
                listener.onResponse(new SearchResponse(InternalSearchResponse.empty(), null, 0, 0, buildTookInMillis(), ShardSearchFailure.EMPTY_ARRAY));
                return;
            }
            int shardIndex = -1;
            for (final ShardIterator shardIt : shardsIts) {
                shardIndex++;
                final ShardRouting shard = shardIt.nextOrNull();
                if (shard != null) {
                    performFirstPhase(shardIndex, shardIt, shard);
                } else {
                    // really, no shards active in this group
                    onFirstPhaseResult(shardIndex, null, null, shardIt, new NoShardAvailableActionException(shardIt.shardId()));
                }
            }
        }

        void performFirstPhase(final int shardIndex, final ShardIterator shardIt, final ShardRouting shard) {
            if (shard == null) {
                // no more active shards... (we should not really get here, but just for safety)
                onFirstPhaseResult(shardIndex, null, null, shardIt, new NoShardAvailableActionException(shardIt.shardId()));
            } else {
                final DiscoveryNode node = nodes.get(shard.currentNodeId());
                if (node == null) {
                    onFirstPhaseResult(shardIndex, shard, null, shardIt, new NoShardAvailableActionException(shardIt.shardId()));
                } else {
                    String[] filteringAliases = indexNameExpressionResolver.filteringAliases(clusterState, shard.index().getName(), request.indices());
                    sendExecuteFirstPhase(node, internalSearchRequest(shard, shardsIts.size(), request, filteringAliases, startTime()), new ActionListener<FirstResult>() {
                        @Override
                        public void onResponse(FirstResult result) {
                            onFirstPhaseResult(shardIndex, shard, result, shardIt);
                        }

                        @Override
                        public void onFailure(Throwable t) {
                            onFirstPhaseResult(shardIndex, shard, node.id(), shardIt, t);
                        }
                    });
                }
            }
        }

        void onFirstPhaseResult(int shardIndex, ShardRouting shard, FirstResult result, ShardIterator shardIt) {
            result.shardTarget(new SearchShardTarget(shard.currentNodeId(), shard.index(), shard.id()));
            processFirstPhaseResult(shardIndex, result);
            // we need to increment successful ops first before we compare the exit condition otherwise if we
            // are fast we could concurrently update totalOps but then preempt one of the threads which can
            // cause the successor to read a wrong value from successfulOps if second phase is very fast ie. count etc.
            successfulOps.incrementAndGet();
            // increment all the "future" shards to update the total ops since we some may work and some may not...
            // and when that happens, we break on total ops, so we must maintain them
            final int xTotalOps = totalOps.addAndGet(shardIt.remaining() + 1);
            if (xTotalOps == expectedTotalOps) {
                try {
                    innerMoveToSecondPhase();
                } catch (Throwable e) {
                    if (logger.isDebugEnabled()) {
                        logger.debug(shardIt.shardId() + ": Failed to execute [" + request + "] while moving to second phase", e);
                    }
                    raiseEarlyFailure(new ReduceSearchPhaseException(firstPhaseName(), "", e, buildShardFailures()));
                }
            } else if (xTotalOps > expectedTotalOps) {
                raiseEarlyFailure(new IllegalStateException("unexpected higher total ops [" + xTotalOps + "] compared to expected [" + expectedTotalOps + "]"));
            }
        }

        void onFirstPhaseResult(final int shardIndex, @Nullable ShardRouting shard, @Nullable String nodeId, final ShardIterator shardIt, Throwable t) {
            // we always add the shard failure for a specific shard instance
            // we do make sure to clean it on a successful response from a shard
            SearchShardTarget shardTarget = new SearchShardTarget(nodeId, shardIt.shardId().getIndex(), shardIt.shardId().getId());
            addShardFailure(shardIndex, shardTarget, t);

            if (totalOps.incrementAndGet() == expectedTotalOps) {
                if (logger.isDebugEnabled()) {
                    if (t != null && !TransportActions.isShardNotAvailableException(t)) {
                        if (shard != null) {
                            logger.debug(shard.shortSummary() + ": Failed to execute [" + request + "]", t);
                        } else {
                            logger.debug(shardIt.shardId() + ": Failed to execute [" + request + "]", t);
                        }
                    } else if (logger.isTraceEnabled()) {
                        logger.trace("{}: Failed to execute [{}]", t, shard, request);
                    }
                }
                final ShardSearchFailure[] shardSearchFailures = buildShardFailures();
                if (successfulOps.get() == 0) {
                    if (logger.isDebugEnabled()) {
                        logger.debug("All shards failed for phase: [{}]", t, firstPhaseName());
                    }

                    // no successful ops, raise an exception
                    raiseEarlyFailure(new SearchPhaseExecutionException(firstPhaseName(), "all shards failed", t, shardSearchFailures));
                } else {
                    try {
                        innerMoveToSecondPhase();
                    } catch (Throwable e) {
                        raiseEarlyFailure(new ReduceSearchPhaseException(firstPhaseName(), "", e, shardSearchFailures));
                    }
                }
            } else {
                final ShardRouting nextShard = shardIt.nextOrNull();
                final boolean lastShard = nextShard == null;
                // trace log this exception
                if (logger.isTraceEnabled()) {
                    logger.trace(executionFailureMsg(shard, shardIt, request, lastShard), t);
                }
                if (!lastShard) {
                    try {
                        performFirstPhase(shardIndex, shardIt, nextShard);
                    } catch (Throwable t1) {
                        onFirstPhaseResult(shardIndex, shard, shard.currentNodeId(), shardIt, t1);
                    }
                } else {
                    // no more shards active, add a failure
                    if (logger.isDebugEnabled() && !logger.isTraceEnabled()) { // do not double log this exception
                        if (t != null && !TransportActions.isShardNotAvailableException(t)) {
                            logger.debug(executionFailureMsg(shard, shardIt, request, lastShard), t);
                        }
                    }
                }
            }
        }

        private String executionFailureMsg(@Nullable ShardRouting shard, final ShardIterator shardIt, SearchRequest request, boolean lastShard) {
            if (shard != null) {
                return shard.shortSummary() + ": Failed to execute [" + request + "] lastShard [" + lastShard + "]";
            } else {
                return shardIt.shardId() + ": Failed to execute [" + request + "] lastShard [" + lastShard + "]";
            }
        }

        protected final ShardSearchFailure[] buildShardFailures() {
            AtomicArray<ShardSearchFailure> shardFailures = this.shardFailures;
            if (shardFailures == null) {
                return ShardSearchFailure.EMPTY_ARRAY;
            }
            List<AtomicArray.Entry<ShardSearchFailure>> entries = shardFailures.asList();
            ShardSearchFailure[] failures = new ShardSearchFailure[entries.size()];
            for (int i = 0; i < failures.length; i++) {
                failures[i] = entries.get(i).value;
            }
            return failures;
        }

        protected final void addShardFailure(final int shardIndex, @Nullable SearchShardTarget shardTarget, Throwable t) {
            // we don't aggregate shard failures on non active shards (but do keep the header counts right)
            if (TransportActions.isShardNotAvailableException(t)) {
                return;
            }

            // lazily create shard failures, so we can early build the empty shard failure list in most cases (no failures)
            if (shardFailures == null) {
                synchronized (shardFailuresMutex) {
                    if (shardFailures == null) {
                        shardFailures = new AtomicArray<>(shardsIts.size());
                    }
                }
            }
            ShardSearchFailure failure = shardFailures.get(shardIndex);
            if (failure == null) {
                shardFailures.set(shardIndex, new ShardSearchFailure(t, shardTarget));
            } else {
                // the failure is already present, try and not override it with an exception that is less meaningless
                // for example, getting illegal shard state
                if (TransportActions.isReadOverrideException(t)) {
                    shardFailures.set(shardIndex, new ShardSearchFailure(t, shardTarget));
                }
            }
        }

        private void raiseEarlyFailure(Throwable t) {
            for (AtomicArray.Entry<FirstResult> entry : firstResults.asList()) {
                try {
                    DiscoveryNode node = nodes.get(entry.value.shardTarget().nodeId());
                    sendReleaseSearchContext(entry.value.id(), node);
                } catch (Throwable t1) {
                    logger.trace("failed to release context", t1);
                }
            }
            listener.onFailure(t);
        }

        /**
         * Releases shard targets that are not used in the docsIdsToLoad.
         */
        protected void releaseIrrelevantSearchContexts(AtomicArray<? extends QuerySearchResultProvider> queryResults,
                                                       AtomicArray<IntArrayList> docIdsToLoad) {
            if (docIdsToLoad == null) {
                return;
            }
            // we only release search context that we did not fetch from if we are not scrolling
            if (request.scroll() == null) {
                for (AtomicArray.Entry<? extends QuerySearchResultProvider> entry : queryResults.asList()) {
                    final TopDocs topDocs = entry.value.queryResult().queryResult().topDocs();
                    if (topDocs != null && topDocs.scoreDocs.length > 0 // the shard had matches
                            && docIdsToLoad.get(entry.index) == null) { // but none of them made it to the global top docs
                        try {
                            DiscoveryNode node = nodes.get(entry.value.queryResult().shardTarget().nodeId());
                            sendReleaseSearchContext(entry.value.queryResult().id(), node);
                        } catch (Throwable t1) {
                            logger.trace("failed to release context", t1);
                        }
                    }
                }
            }
        }

        protected void sendReleaseSearchContext(long contextId, DiscoveryNode node) {
            if (node != null) {
                searchService.sendFreeContext(node, contextId, request);
            }
        }

        protected ShardFetchSearchRequest createFetchRequest(QuerySearchResult queryResult, AtomicArray.Entry<IntArrayList> entry, ScoreDoc[] lastEmittedDocPerShard) {
            if (lastEmittedDocPerShard != null) {
                ScoreDoc lastEmittedDoc = lastEmittedDocPerShard[entry.index];
                return new ShardFetchSearchRequest(request, queryResult.id(), entry.value, lastEmittedDoc);
            } else {
                return new ShardFetchSearchRequest(request, queryResult.id(), entry.value);
            }
        }

        protected abstract void sendExecuteFirstPhase(DiscoveryNode node, ShardSearchTransportRequest request, ActionListener<FirstResult> listener);

        protected final void processFirstPhaseResult(int shardIndex, FirstResult result) {
            firstResults.set(shardIndex, result);

            if (logger.isTraceEnabled()) {
                logger.trace("got first-phase result from {}", result != null ? result.shardTarget() : null);
            }

            // clean a previous error on this shard group (note, this code will be serialized on the same shardIndex value level
            // so its ok concurrency wise to miss potentially the shard failures being created because of another failure
            // in the #addShardFailure, because by definition, it will happen on *another* shardIndex
            AtomicArray<ShardSearchFailure> shardFailures = this.shardFailures;
            if (shardFailures != null) {
                shardFailures.set(shardIndex, null);
            }
        }

        final void innerMoveToSecondPhase() throws Exception {
            if (logger.isTraceEnabled()) {
                StringBuilder sb = new StringBuilder();
                boolean hadOne = false;
                for (int i = 0; i < firstResults.length(); i++) {
                    FirstResult result = firstResults.get(i);
                    if (result == null) {
                        continue; // failure
                    }
                    if (hadOne) {
                        sb.append(",");
                    } else {
                        hadOne = true;
                    }
                    sb.append(result.shardTarget());
                }

                logger.trace("Moving to second phase, based on results from: {} (cluster state version: {})", sb, clusterState.version());
            }
            moveToSecondPhase();
        }

        protected abstract void moveToSecondPhase() throws Exception;

        protected abstract String firstPhaseName();
    }
}