|
| 1 | +/* |
| 2 | + * Licensed to Elasticsearch under one or more contributor |
| 3 | + * license agreements. See the NOTICE file distributed with |
| 4 | + * this work for additional information regarding copyright |
| 5 | + * ownership. Elasticsearch licenses this file to you under |
| 6 | + * the Apache License, Version 2.0 (the "License"); you may |
| 7 | + * not use this file except in compliance with the License. |
| 8 | + * You may obtain a copy of the License at |
| 9 | + * |
| 10 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 11 | + * |
| 12 | + * Unless required by applicable law or agreed to in writing, |
| 13 | + * software distributed under the License is distributed on an |
| 14 | + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY |
| 15 | + * KIND, either express or implied. See the License for the |
| 16 | + * specific language governing permissions and limitations |
| 17 | + * under the License. |
| 18 | + */ |
| 19 | +package org.elasticsearch.client; |
| 20 | + |
| 21 | +import org.elasticsearch.action.admin.indices.refresh.RefreshRequest; |
| 22 | +import org.elasticsearch.action.bulk.BackoffPolicy; |
| 23 | +import org.elasticsearch.action.bulk.BulkItemResponse; |
| 24 | +import org.elasticsearch.action.bulk.BulkProcessor; |
| 25 | +import org.elasticsearch.action.bulk.BulkRequest; |
| 26 | +import org.elasticsearch.action.bulk.BulkResponse; |
| 27 | +import org.elasticsearch.action.get.MultiGetRequest; |
| 28 | +import org.elasticsearch.action.index.IndexRequest; |
| 29 | +import org.elasticsearch.common.unit.TimeValue; |
| 30 | +import org.elasticsearch.common.xcontent.XContentType; |
| 31 | +import org.elasticsearch.rest.RestStatus; |
| 32 | + |
| 33 | +import java.util.Collections; |
| 34 | +import java.util.Iterator; |
| 35 | +import java.util.Map; |
| 36 | +import java.util.Set; |
| 37 | +import java.util.concurrent.ConcurrentHashMap; |
| 38 | +import java.util.concurrent.CountDownLatch; |
| 39 | +import java.util.concurrent.TimeUnit; |
| 40 | + |
| 41 | +import static org.hamcrest.Matchers.equalTo; |
| 42 | +import static org.hamcrest.Matchers.lessThan; |
| 43 | +import static org.hamcrest.Matchers.lessThanOrEqualTo; |
| 44 | + |
| 45 | +public class BulkProcessorRetryIT extends ESRestHighLevelClientTestCase { |
| 46 | + |
| 47 | + private static final String INDEX_NAME = "index"; |
| 48 | + private static final String TYPE_NAME = "type"; |
| 49 | + |
| 50 | + private static BulkProcessor.Builder initBulkProcessorBuilder(BulkProcessor.Listener listener) { |
| 51 | + return BulkProcessor.builder(highLevelClient()::bulkAsync, listener); |
| 52 | + } |
| 53 | + |
| 54 | + public void testBulkRejectionLoadWithoutBackoff() throws Exception { |
| 55 | + boolean rejectedExecutionExpected = true; |
| 56 | + executeBulkRejectionLoad(BackoffPolicy.noBackoff(), rejectedExecutionExpected); |
| 57 | + } |
| 58 | + |
| 59 | + public void testBulkRejectionLoadWithBackoff() throws Throwable { |
| 60 | + boolean rejectedExecutionExpected = false; |
| 61 | + executeBulkRejectionLoad(BackoffPolicy.exponentialBackoff(), rejectedExecutionExpected); |
| 62 | + } |
| 63 | + |
| 64 | + private void executeBulkRejectionLoad(BackoffPolicy backoffPolicy, boolean rejectedExecutionExpected) throws Exception { |
| 65 | + final CorrelatingBackoffPolicy internalPolicy = new CorrelatingBackoffPolicy(backoffPolicy); |
| 66 | + final int numberOfAsyncOps = randomIntBetween(600, 700); |
| 67 | + final CountDownLatch latch = new CountDownLatch(numberOfAsyncOps); |
| 68 | + final Set<Object> responses = Collections.newSetFromMap(new ConcurrentHashMap<>()); |
| 69 | + |
| 70 | + BulkProcessor bulkProcessor = initBulkProcessorBuilder(new BulkProcessor.Listener() { |
| 71 | + @Override |
| 72 | + public void beforeBulk(long executionId, BulkRequest request) { |
| 73 | + } |
| 74 | + |
| 75 | + @Override |
| 76 | + public void afterBulk(long executionId, BulkRequest request, BulkResponse response) { |
| 77 | + internalPolicy.logResponse(response); |
| 78 | + responses.add(response); |
| 79 | + latch.countDown(); |
| 80 | + } |
| 81 | + |
| 82 | + @Override |
| 83 | + public void afterBulk(long executionId, BulkRequest request, Throwable failure) { |
| 84 | + responses.add(failure); |
| 85 | + latch.countDown(); |
| 86 | + } |
| 87 | + }).setBulkActions(1) |
| 88 | + .setConcurrentRequests(randomIntBetween(0, 100)) |
| 89 | + .setBackoffPolicy(internalPolicy) |
| 90 | + .build(); |
| 91 | + |
| 92 | + MultiGetRequest multiGetRequest = indexDocs(bulkProcessor, numberOfAsyncOps); |
| 93 | + latch.await(10, TimeUnit.SECONDS); |
| 94 | + bulkProcessor.close(); |
| 95 | + |
| 96 | + assertEquals(responses.size(), numberOfAsyncOps); |
| 97 | + |
| 98 | + boolean rejectedAfterAllRetries = false; |
| 99 | + for (Object response : responses) { |
| 100 | + if (response instanceof BulkResponse) { |
| 101 | + BulkResponse bulkResponse = (BulkResponse) response; |
| 102 | + for (BulkItemResponse bulkItemResponse : bulkResponse.getItems()) { |
| 103 | + if (bulkItemResponse.isFailed()) { |
| 104 | + BulkItemResponse.Failure failure = bulkItemResponse.getFailure(); |
| 105 | + if (failure.getStatus() == RestStatus.TOO_MANY_REQUESTS) { |
| 106 | + if (rejectedExecutionExpected == false) { |
| 107 | + Iterator<TimeValue> backoffState = internalPolicy.backoffStateFor(bulkResponse); |
| 108 | + assertNotNull("backoffState is null (indicates a bulk request got rejected without retry)", backoffState); |
| 109 | + if (backoffState.hasNext()) { |
| 110 | + // we're not expecting that we overwhelmed it even once when we maxed out the number of retries |
| 111 | + throw new AssertionError("Got rejected although backoff policy would allow more retries", |
| 112 | + failure.getCause()); |
| 113 | + } else { |
| 114 | + rejectedAfterAllRetries = true; |
| 115 | + logger.debug("We maxed out the number of bulk retries and got rejected (this is ok)."); |
| 116 | + } |
| 117 | + } |
| 118 | + } else { |
| 119 | + throw new AssertionError("Unexpected failure with status: " + failure.getStatus()); |
| 120 | + } |
| 121 | + } |
| 122 | + } |
| 123 | + } else { |
| 124 | + Throwable t = (Throwable) response; |
| 125 | + // we're not expecting any other errors |
| 126 | + throw new AssertionError("Unexpected failure", t); |
| 127 | + } |
| 128 | + } |
| 129 | + |
| 130 | + highLevelClient().indices().refresh(new RefreshRequest()); |
| 131 | + int multiGetResponsesCount = highLevelClient().multiGet(multiGetRequest).getResponses().length; |
| 132 | + |
| 133 | + if (rejectedExecutionExpected) { |
| 134 | + assertThat(multiGetResponsesCount, lessThanOrEqualTo(numberOfAsyncOps)); |
| 135 | + } else if (rejectedAfterAllRetries) { |
| 136 | + assertThat(multiGetResponsesCount, lessThan(numberOfAsyncOps)); |
| 137 | + } else { |
| 138 | + assertThat(multiGetResponsesCount, equalTo(numberOfAsyncOps)); |
| 139 | + } |
| 140 | + |
| 141 | + } |
| 142 | + |
| 143 | + private static MultiGetRequest indexDocs(BulkProcessor processor, int numDocs) { |
| 144 | + MultiGetRequest multiGetRequest = new MultiGetRequest(); |
| 145 | + for (int i = 1; i <= numDocs; i++) { |
| 146 | + processor.add(new IndexRequest(INDEX_NAME, TYPE_NAME, Integer.toString(i)) |
| 147 | + .source(XContentType.JSON, "field", randomRealisticUnicodeOfCodepointLengthBetween(1, 30))); |
| 148 | + multiGetRequest.add(INDEX_NAME, TYPE_NAME, Integer.toString(i)); |
| 149 | + } |
| 150 | + return multiGetRequest; |
| 151 | + } |
| 152 | + |
| 153 | + /** |
| 154 | + * Internal helper class to correlate backoff states with bulk responses. This is needed to check whether we maxed out the number |
| 155 | + * of retries but still got rejected (which is perfectly fine and can also happen from time to time under heavy load). |
| 156 | + * |
| 157 | + * This implementation relies on an implementation detail in Retry, namely that the bulk listener is notified on the same thread |
| 158 | + * as the last call to the backoff policy's iterator. The advantage is that this is non-invasive to the rest of the production code. |
| 159 | + */ |
| 160 | + private static class CorrelatingBackoffPolicy extends BackoffPolicy { |
| 161 | + private final Map<BulkResponse, Iterator<TimeValue>> correlations = new ConcurrentHashMap<>(); |
| 162 | + // this is intentionally *not* static final. We will only ever have one instance of this class per test case and want the |
| 163 | + // thread local to be eligible for garbage collection right after the test to avoid leaks. |
| 164 | + private final ThreadLocal<Iterator<TimeValue>> iterators = new ThreadLocal<>(); |
| 165 | + |
| 166 | + private final BackoffPolicy delegate; |
| 167 | + |
| 168 | + private CorrelatingBackoffPolicy(BackoffPolicy delegate) { |
| 169 | + this.delegate = delegate; |
| 170 | + } |
| 171 | + |
| 172 | + public Iterator<TimeValue> backoffStateFor(BulkResponse response) { |
| 173 | + return correlations.get(response); |
| 174 | + } |
| 175 | + |
| 176 | + // Assumption: This method is called from the same thread as the last call to the internal iterator's #hasNext() / #next() |
| 177 | + // see also Retry.AbstractRetryHandler#onResponse(). |
| 178 | + public void logResponse(BulkResponse response) { |
| 179 | + Iterator<TimeValue> iterator = iterators.get(); |
| 180 | + // did we ever retry? |
| 181 | + if (iterator != null) { |
| 182 | + // we should correlate any iterator only once |
| 183 | + iterators.remove(); |
| 184 | + correlations.put(response, iterator); |
| 185 | + } |
| 186 | + } |
| 187 | + |
| 188 | + @Override |
| 189 | + public Iterator<TimeValue> iterator() { |
| 190 | + return new CorrelatingIterator(iterators, delegate.iterator()); |
| 191 | + } |
| 192 | + |
| 193 | + private static class CorrelatingIterator implements Iterator<TimeValue> { |
| 194 | + private final Iterator<TimeValue> delegate; |
| 195 | + private final ThreadLocal<Iterator<TimeValue>> iterators; |
| 196 | + |
| 197 | + private CorrelatingIterator(ThreadLocal<Iterator<TimeValue>> iterators, Iterator<TimeValue> delegate) { |
| 198 | + this.iterators = iterators; |
| 199 | + this.delegate = delegate; |
| 200 | + } |
| 201 | + |
| 202 | + @Override |
| 203 | + public boolean hasNext() { |
| 204 | + // update on every invocation as we might get rescheduled on a different thread. Unfortunately, there is a chance that |
| 205 | + // we pollute the thread local map with stale values. Due to the implementation of Retry and the life cycle of the |
| 206 | + // enclosing class CorrelatingBackoffPolicy this should not pose a major problem though. |
| 207 | + iterators.set(this); |
| 208 | + return delegate.hasNext(); |
| 209 | + } |
| 210 | + |
| 211 | + @Override |
| 212 | + public TimeValue next() { |
| 213 | + // update on every invocation |
| 214 | + iterators.set(this); |
| 215 | + return delegate.next(); |
| 216 | + } |
| 217 | + } |
| 218 | + } |
| 219 | +} |
0 commit comments