Skip to content

Apache Lucene open-source search software

SOLR-13528: Implement Request Rate Limiters (#1686)

Atri Sharmaa074418da0d0
diff --git a/solr/CHANGES.txt b/solr/CHANGES.txt
index 2cc9710527b..5df42149981 100644
--- a/solr/CHANGES.txt
+++ b/solr/CHANGES.txt
@@ -38,6 +38,10 @@ Improvements
* SOLR-10814: Add short-name feature to RuleBasedAuthz plugin (Mike Drob, Hrishikesh Gadre)
+* SOLR-7683 Introduce support to identify Solr internal request types (Atri Sharma, Hrishikesh Gadre)
+
+* SOLR-13528 Rate Limiting in Solr (Atri Sharma, Mike Drob)
+
Other Changes
----------------------
* SOLR-14656: Autoscaling framework removed (Ishan Chattopadhyaya, noble, Ilan Ginzburg)
diff --git a/solr/core/src/java/org/apache/solr/handler/SolrConfigHandler.java b/solr/core/src/java/org/apache/solr/handler/SolrConfigHandler.java
index 4940af29bfa..bf599411761 100644
--- a/solr/core/src/java/org/apache/solr/handler/SolrConfigHandler.java
+++ b/solr/core/src/java/org/apache/solr/handler/SolrConfigHandler.java
@@ -945,6 +945,11 @@ public class SolrConfigHandler extends RequestHandlerBase implements SolrCoreAwa
protected SolrResponse createResponse(SolrClient client) {
return null;
}
+
+ @Override
+ public String getRequestType() {
+ return SolrRequest.SolrRequestType.ADMIN.toString();
+ }
}
@Override
diff --git a/solr/core/src/java/org/apache/solr/schema/ManagedIndexSchema.java b/solr/core/src/java/org/apache/solr/schema/ManagedIndexSchema.java
index d44e9619cc2..9fd52431a44 100644
--- a/solr/core/src/java/org/apache/solr/schema/ManagedIndexSchema.java
+++ b/solr/core/src/java/org/apache/solr/schema/ManagedIndexSchema.java
@@ -372,6 +372,11 @@ public final class ManagedIndexSchema extends IndexSchema {
return null;
}
+ @Override
+ public String getRequestType() {
+ return SolrRequest.SolrRequestType.ADMIN.toString();
+ }
+
}
diff --git a/solr/core/src/java/org/apache/solr/servlet/QueryRateLimiter.java b/solr/core/src/java/org/apache/solr/servlet/QueryRateLimiter.java
new file mode 100644
index 00000000000..ca2f6960b31
--- /dev/null
+++ b/solr/core/src/java/org/apache/solr/servlet/QueryRateLimiter.java
@@ -0,0 +1,55 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF 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.apache.solr.servlet;
+
+import javax.servlet.FilterConfig;
+
+import org.apache.solr.client.solrj.SolrRequest;
+
+import static org.apache.solr.servlet.RateLimitManager.DEFAULT_CONCURRENT_REQUESTS;
+import static org.apache.solr.servlet.RateLimitManager.DEFAULT_SLOT_ACQUISITION_TIMEOUT_MS;
+
+/** Implementation of RequestRateLimiter specific to query request types. Most of the actual work is delegated
+ * to the parent class but specific configurations and parsing are handled by this class.
+ */
+public class QueryRateLimiter extends RequestRateLimiter {
+ final static String IS_QUERY_RATE_LIMITER_ENABLED = "isQueryRateLimiterEnabled";
+ final static String MAX_QUERY_REQUESTS = "maxQueryRequests";
+ final static String QUERY_WAIT_FOR_SLOT_ALLOCATION_INMS = "queryWaitForSlotAllocationInMS";
+ final static String QUERY_GUARANTEED_SLOTS = "queryGuaranteedSlots";
+ final static String QUERY_ALLOW_SLOT_BORROWING = "queryAllowSlotBorrowing";
+
+ public QueryRateLimiter(FilterConfig filterConfig) {
+ super(constructQueryRateLimiterConfig(filterConfig));
+ }
+
+ protected static RequestRateLimiter.RateLimiterConfig constructQueryRateLimiterConfig(FilterConfig filterConfig) {
+ RequestRateLimiter.RateLimiterConfig queryRateLimiterConfig = new RequestRateLimiter.RateLimiterConfig();
+
+ queryRateLimiterConfig.requestType = SolrRequest.SolrRequestType.QUERY;
+ queryRateLimiterConfig.isEnabled = getParamAndParseBoolean(filterConfig, IS_QUERY_RATE_LIMITER_ENABLED, false);
+ queryRateLimiterConfig.waitForSlotAcquisition = getParamAndParseLong(filterConfig, QUERY_WAIT_FOR_SLOT_ALLOCATION_INMS,
+ DEFAULT_SLOT_ACQUISITION_TIMEOUT_MS);
+ queryRateLimiterConfig.allowedRequests = getParamAndParseInt(filterConfig, MAX_QUERY_REQUESTS,
+ DEFAULT_CONCURRENT_REQUESTS);
+ queryRateLimiterConfig.isSlotBorrowingEnabled = getParamAndParseBoolean(filterConfig, QUERY_ALLOW_SLOT_BORROWING, false);
+ queryRateLimiterConfig.guaranteedSlotsThreshold = getParamAndParseInt(filterConfig, QUERY_GUARANTEED_SLOTS, queryRateLimiterConfig.allowedRequests / 2);
+
+ return queryRateLimiterConfig;
+ }
+}
diff --git a/solr/core/src/java/org/apache/solr/servlet/RateLimitManager.java b/solr/core/src/java/org/apache/solr/servlet/RateLimitManager.java
new file mode 100644
index 00000000000..0f4618a9c20
--- /dev/null
+++ b/solr/core/src/java/org/apache/solr/servlet/RateLimitManager.java
@@ -0,0 +1,181 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF 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.apache.solr.servlet;
+
+import javax.servlet.FilterConfig;
+import javax.servlet.http.HttpServletRequest;
+import java.lang.invoke.MethodHandles;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+
+import org.apache.solr.client.solrj.SolrRequest;
+import org.apache.solr.common.annotation.SolrThreadSafe;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import static org.apache.solr.common.params.CommonParams.SOLR_REQUEST_CONTEXT_PARAM;
+import static org.apache.solr.common.params.CommonParams.SOLR_REQUEST_TYPE_PARAM;
+
+/**
+ * This class is responsible for managing rate limiting per request type. Rate limiters
+ * can be registered with this class against a corresponding type. There can be only one
+ * rate limiter associated with a request type.
+ *
+ * The actual rate limiting and the limits should be implemented in the corresponding RequestRateLimiter
+ * implementation. RateLimitManager is responsible for the orchestration but not the specifics of how the
+ * rate limiting is being done for a specific request type.
+ */
+@SolrThreadSafe
+public class RateLimitManager {
+ private static final Logger log = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
+
+ public final static int DEFAULT_CONCURRENT_REQUESTS= (Runtime.getRuntime().availableProcessors()) * 3;
+ public final static long DEFAULT_SLOT_ACQUISITION_TIMEOUT_MS = -1;
+ private final Map<String, RequestRateLimiter> requestRateLimiterMap;
+
+ private final Map<HttpServletRequest, RequestRateLimiter.SlotMetadata> activeRequestsMap;
+
+ public RateLimitManager() {
+ this.requestRateLimiterMap = new HashMap<>();
+ this.activeRequestsMap = new ConcurrentHashMap<>();
+ }
+
+ // Handles an incoming request. The main orchestration code path, this method will
+ // identify which (if any) rate limiter can handle this request. Internal requests will not be
+ // rate limited
+ // Returns true if request is accepted for processing, false if it should be rejected
+ public boolean handleRequest(HttpServletRequest request) throws InterruptedException {
+ String requestContext = request.getHeader(SOLR_REQUEST_CONTEXT_PARAM);
+ String typeOfRequest = request.getHeader(SOLR_REQUEST_TYPE_PARAM);
+
+ if (typeOfRequest == null) {
+ // Cannot determine if this request should be throttled
+ return true;
+ }
+
+ // Do not throttle internal requests
+ if (requestContext != null && requestContext.equals(SolrRequest.SolrClientContext.SERVER.toString())) {
+ return true;
+ }
+
+ RequestRateLimiter requestRateLimiter = requestRateLimiterMap.get(typeOfRequest);
+
+ if (requestRateLimiter == null) {
+ // No request rate limiter for this request type
+ return true;
+ }
+
+ RequestRateLimiter.SlotMetadata result = requestRateLimiter.handleRequest();
+
+ if (result != null) {
+ // Can be the case if request rate limiter is disabled
+ if (result.isReleasable()) {
+ activeRequestsMap.put(request, result);
+ }
+ return true;
+ }
+
+ RequestRateLimiter.SlotMetadata slotMetadata = trySlotBorrowing(typeOfRequest);
+
+ if (slotMetadata != null) {
+ activeRequestsMap.put(request, slotMetadata);
+ return true;
+ }
+
+ return false;
+ }
+
+ /* For a rejected request type, do the following:
+ * For each request rate limiter whose type that is not of the type of the request which got rejected,
+ * check if slot borrowing is enabled. If enabled, try to acquire a slot.
+ * If allotted, return else try next request type.
+ *
+ * @lucene.experimental -- Can cause slots to be blocked if a request borrows a slot and is itself long lived.
+ */
+ private RequestRateLimiter.SlotMetadata trySlotBorrowing(String requestType) {
+ for (Map.Entry<String, RequestRateLimiter> currentEntry : requestRateLimiterMap.entrySet()) {
+ RequestRateLimiter.SlotMetadata result = null;
+ RequestRateLimiter requestRateLimiter = currentEntry.getValue();
+
+ // Cant borrow from ourselves
+ if (requestRateLimiter.getRateLimiterConfig().requestType.toString().equals(requestType)) {
+ continue;
+ }
+
+ if (requestRateLimiter.getRateLimiterConfig().isSlotBorrowingEnabled) {
+ if (log.isWarnEnabled()) {
+ String msg = "WARN: Experimental feature slots borrowing is enabled for request rate limiter type " +
+ requestRateLimiter.getRateLimiterConfig().requestType.toString();
+
+ log.warn(msg);
+ }
+
+ try {
+ result = requestRateLimiter.allowSlotBorrowing();
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ }
+
+ if (result == null) {
+ throw new IllegalStateException("Returned metadata object is null");
+ }
+
+ if (result.isReleasable()) {
+ return result;
+ }
+ }
+ }
+
+ return null;
+ }
+
+ // Decrement the active requests in the rate limiter for the corresponding request type.
+ public void decrementActiveRequests(HttpServletRequest request) {
+ RequestRateLimiter.SlotMetadata slotMetadata = activeRequestsMap.get(request);
+
+ if (slotMetadata != null) {
+ activeRequestsMap.remove(request);
+ slotMetadata.decrementRequest();
+ }
+ }
+
+ public void registerRequestRateLimiter(RequestRateLimiter requestRateLimiter, SolrRequest.SolrRequestType requestType) {
+ requestRateLimiterMap.put(requestType.toString(), requestRateLimiter);
+ }
+
+ public RequestRateLimiter getRequestRateLimiter(SolrRequest.SolrRequestType requestType) {
+ return requestRateLimiterMap.get(requestType.toString());
+ }
+
+ public static class Builder {
+ protected FilterConfig config;
+
+ public Builder(FilterConfig config) {
+ this.config = config;
+ }
+
+ public RateLimitManager build() {
+ RateLimitManager rateLimitManager = new RateLimitManager();
+
+ rateLimitManager.registerRequestRateLimiter(new QueryRateLimiter(config), SolrRequest.SolrRequestType.QUERY);
+
+ return rateLimitManager;
+ }
+ }
+}
diff --git a/solr/core/src/java/org/apache/solr/servlet/RequestRateLimiter.java b/solr/core/src/java/org/apache/solr/servlet/RequestRateLimiter.java
new file mode 100644
index 00000000000..f68b31266ac
--- /dev/null
+++ b/solr/core/src/java/org/apache/solr/servlet/RequestRateLimiter.java
@@ -0,0 +1,168 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF 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.apache.solr.servlet;
+
+import javax.servlet.FilterConfig;
+import java.util.concurrent.Semaphore;
+import java.util.concurrent.TimeUnit;
+
+import org.apache.solr.client.solrj.SolrRequest;
+import org.apache.solr.common.annotation.SolrThreadSafe;
+
+/**
+ * Handles rate limiting for a specific request type.
+ *
+ * The control flow is as follows:
+ * Handle request -- Check if slot is available -- If available, acquire slot and proceed --
+ * else reject the same.
+ */
+@SolrThreadSafe
+public class RequestRateLimiter {
+ // Slots that are guaranteed for this request rate limiter.
+ private final Semaphore guaranteedSlotsPool;
+
+ // Competitive slots pool that are available for this rate limiter as well as borrowing by other request rate limiters.
+ // By competitive, the meaning is that there is no prioritization for the acquisition of these slots -- First Come First Serve,
+ // irrespective of whether the request is of this request rate limiter or other.
+ private final Semaphore borrowableSlotsPool;
+
+ private final RateLimiterConfig rateLimiterConfig;
+ private final SlotMetadata guaranteedSlotMetadata;
+ private final SlotMetadata borrowedSlotMetadata;
+ private static final SlotMetadata nullSlotMetadata = new SlotMetadata(null);
+
+ public RequestRateLimiter(RateLimiterConfig rateLimiterConfig) {
+ this.rateLimiterConfig = rateLimiterConfig;
+ this.guaranteedSlotsPool = new Semaphore(rateLimiterConfig.guaranteedSlotsThreshold);
+ this.borrowableSlotsPool = new Semaphore(rateLimiterConfig.allowedRequests - rateLimiterConfig.guaranteedSlotsThreshold);
+ this.guaranteedSlotMetadata = new SlotMetadata(guaranteedSlotsPool);
+ this.borrowedSlotMetadata = new SlotMetadata(borrowableSlotsPool);
+ }
+
+ /**
+ * Handles an incoming request. returns a metadata object representing the metadata for the acquired slot, if acquired.
+ * If a slot is not acquired, returns a null metadata object.
+ * */
+ public SlotMetadata handleRequest() throws InterruptedException {
+
+ if (!rateLimiterConfig.isEnabled) {
+ return nullSlotMetadata;
+ }
+
+ if (guaranteedSlotsPool.tryAcquire(rateLimiterConfig.waitForSlotAcquisition, TimeUnit.MILLISECONDS)) {
+ return guaranteedSlotMetadata;
+ }
+
+ if (borrowableSlotsPool.tryAcquire(rateLimiterConfig.waitForSlotAcquisition, TimeUnit.MILLISECONDS)) {
+ return borrowedSlotMetadata;
+ }
+
+ return null;
+ }
+
+ /**
+ * Whether to allow another request type to borrow a slot from this request rate limiter. Typically works fine
+ * if there is a relatively lesser load on this request rate limiter's type compared to the others (think of skew).
+ * @return returns a metadata object for the acquired slot, if acquired. If the
+ * slot was not acquired, returns a metadata object with a null pool.
+ *
+ * @lucene.experimental -- Can cause slots to be blocked if a request borrows a slot and is itself long lived.
+ */
+ public SlotMetadata allowSlotBorrowing() throws InterruptedException {
+ if (borrowableSlotsPool.tryAcquire(rateLimiterConfig.waitForSlotAcquisition, TimeUnit.MILLISECONDS)) {
+ return borrowedSlotMetadata;
+ }
+
+ return nullSlotMetadata;
+ }
+
+ public RateLimiterConfig getRateLimiterConfig() {
+ return rateLimiterConfig;
+ }
+
+ static long getParamAndParseLong(FilterConfig config, String parameterName, long defaultValue) {
+ String tempBuffer = config.getInitParameter(parameterName);
+
+ if (tempBuffer != null) {
+ return Long.parseLong(tempBuffer);
+ }
+
+ return defaultValue;
+ }
+
+ static int getParamAndParseInt(FilterConfig config, String parameterName, int defaultValue) {
+ String tempBuffer = config.getInitParameter(parameterName);
+
+ if (tempBuffer != null) {
+ return Integer.parseInt(tempBuffer);
+ }
+
+ return defaultValue;
+ }
+
+ static boolean getParamAndParseBoolean(FilterConfig config, String parameterName, boolean defaultValue) {
+ String tempBuffer = config.getInitParameter(parameterName);
+
+ if (tempBuffer != null) {
+ return Boolean.parseBoolean(tempBuffer);
+ }
+
+ return defaultValue;
+ }
+
+ /* Rate limiter config for a specific request rate limiter instance */
+ static class RateLimiterConfig {
+ public SolrRequest.SolrRequestType requestType;
+ public boolean isEnabled;
+ public long waitForSlotAcquisition;
+ public int allowedRequests;
+ public boolean isSlotBorrowingEnabled;
+ public int guaranteedSlotsThreshold;
+
+ public RateLimiterConfig() { }
+
+ public RateLimiterConfig(SolrRequest.SolrRequestType requestType, boolean isEnabled, int guaranteedSlotsThreshold,
+ long waitForSlotAcquisition, int allowedRequests, boolean isSlotBorrowingEnabled) {
+ this.requestType = requestType;
+ this.isEnabled = isEnabled;
+ this.guaranteedSlotsThreshold = guaranteedSlotsThreshold;
+ this.waitForSlotAcquisition = waitForSlotAcquisition;
+ this.allowedRequests = allowedRequests;
+ this.isSlotBorrowingEnabled = isSlotBorrowingEnabled;
+ }
+ }
+
+ // Represents the metadata for a slot
+ static class SlotMetadata {
+ private final Semaphore usedPool;
+
+ public SlotMetadata(Semaphore usedPool) {
+ this.usedPool = usedPool;
+ }
+
+ public void decrementRequest() {
+ if (usedPool != null) {
+ usedPool.release();
+ }
+ }
+
+ public boolean isReleasable() {
+ return usedPool != null;
+ }
+ }
+}
diff --git a/solr/core/src/java/org/apache/solr/servlet/SolrDispatchFilter.java b/solr/core/src/java/org/apache/solr/servlet/SolrDispatchFilter.java
index a7d89055a05..b6c0f4247a4 100644
--- a/solr/core/src/java/org/apache/solr/servlet/SolrDispatchFilter.java
+++ b/solr/core/src/java/org/apache/solr/servlet/SolrDispatchFilter.java
@@ -53,6 +53,7 @@ import com.codahale.metrics.jvm.ClassLoadingGaugeSet;
import com.codahale.metrics.jvm.GarbageCollectorMetricSet;
import com.codahale.metrics.jvm.MemoryUsageGaugeSet;
import com.codahale.metrics.jvm.ThreadStatesGaugeSet;
+import com.google.common.annotations.VisibleForTesting;
import io.opentracing.Scope;
import io.opentracing.Span;
import io.opentracing.SpanContext;
@@ -71,8 +72,8 @@ import org.apache.solr.core.CoreContainer;
import org.apache.solr.core.NodeConfig;
import org.apache.solr.core.SolrCore;
import org.apache.solr.core.SolrInfoBean;
-import org.apache.solr.core.SolrXmlConfig;
import org.apache.solr.core.SolrPaths;
+import org.apache.solr.core.SolrXmlConfig;
import org.apache.solr.metrics.AltBufferPoolMetricSet;
import org.apache.solr.metrics.MetricsMap;
import org.apache.solr.metrics.OperatingSystemMetricSet;
@@ -83,9 +84,9 @@ import org.apache.solr.security.AuditEvent;
import org.apache.solr.security.AuthenticationPlugin;
import org.apache.solr.security.PKIAuthenticationPlugin;
import org.apache.solr.security.PublicKeyHandler;
-import org.apache.solr.util.tracing.GlobalTracer;
import org.apache.solr.util.StartupLoggingUtils;
import org.apache.solr.util.configuration.SSLConfigurationsFactory;
+import org.apache.solr.util.tracing.GlobalTracer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -114,6 +115,8 @@ public class SolrDispatchFilter extends BaseSolrFilter {
private String registryName;
private volatile boolean closeOnDestroy = true;
+ private RateLimitManager rateLimitManager;
+
/**
* Enum to define action that needs to be processed.
* PASSTHROUGH: Pass through to Restlet via webapp.
@@ -184,6 +187,9 @@ public class SolrDispatchFilter extends BaseSolrFilter {
coresInit = createCoreContainer(solrHomePath, extraProperties);
this.httpClient = coresInit.getUpdateShardHandler().getDefaultHttpClient();
setupJvmMetrics(coresInit);
+ RateLimitManager.Builder builder = new RateLimitManager.Builder(config);
+
+ this.rateLimitManager = builder.build();
if (log.isDebugEnabled()) {
log.debug("user.dir={}", System.getProperty("user.dir"));
}
@@ -351,6 +357,7 @@ public class SolrDispatchFilter extends BaseSolrFilter {
HttpServletResponse response = closeShield((HttpServletResponse)_response, retry);
Scope scope = null;
Span span = null;
+ boolean accepted = false;
try {
if (cores == null || cores.isShutDown()) {
@@ -377,6 +384,20 @@ public class SolrDispatchFilter extends BaseSolrFilter {
}
}
+ try {
+ accepted = rateLimitManager.handleRequest(request);
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ throw new SolrException(ErrorCode.SERVER_ERROR, e.getMessage());
+ }
+
+ if (!accepted) {
+ String errorMessage = "Too many requests for this request type." +
+ "Please try after some time or increase the quota for this request type";
+
+ response.sendError(429, errorMessage);
+ }
+
SpanContext parentSpan = GlobalTracer.get().extract(request);
Tracer tracer = GlobalTracer.getTracer();
@@ -399,6 +420,7 @@ public class SolrDispatchFilter extends BaseSolrFilter {
if (!authenticateRequest(request, response, wrappedRequest)) { // the response and status code have already been sent
return;
}
+
if (wrappedRequest.get() != null) {
request = wrappedRequest.get();
}
@@ -441,6 +463,10 @@ public class SolrDispatchFilter extends BaseSolrFilter {
consumeInputFully(request, response);
SolrRequestInfo.reset();
SolrRequestParsers.cleanupMultipartFiles(request);
+
+ if (accepted) {
+ rateLimitManager.decrementActiveRequests(request);
+ }
}
}
@@ -664,8 +690,13 @@ public class SolrDispatchFilter extends BaseSolrFilter {
return response;
}
}
-
+
public void closeOnDestroy(boolean closeOnDestroy) {
this.closeOnDestroy = closeOnDestroy;
}
+
+ @VisibleForTesting
+ void replaceRateLimitManager(RateLimitManager rateLimitManager) {
+ this.rateLimitManager = rateLimitManager;
+ }
}
diff --git a/solr/core/src/test/org/apache/solr/client/solrj/embedded/TestEmbeddedSolrServerAdminHandler.java b/solr/core/src/test/org/apache/solr/client/solrj/embedded/TestEmbeddedSolrServerAdminHandler.java
index b5faba24097..19d6dbe0ca0 100644
--- a/solr/core/src/test/org/apache/solr/client/solrj/embedded/TestEmbeddedSolrServerAdminHandler.java
+++ b/solr/core/src/test/org/apache/solr/client/solrj/embedded/TestEmbeddedSolrServerAdminHandler.java
@@ -61,6 +61,11 @@ public class TestEmbeddedSolrServerAdminHandler extends SolrTestCaseJ4 {
protected QueryResponse createResponse(final SolrClient client) {
return new QueryResponse();
}
+
+ @Override
+ public String getRequestType() {
+ return SolrRequest.SolrRequestType.ADMIN.toString();
+ }
}
}
diff --git a/solr/core/src/test/org/apache/solr/pkg/TestPackages.java b/solr/core/src/test/org/apache/solr/pkg/TestPackages.java
index 1566759764c..8d8583c11a4 100644
--- a/solr/core/src/test/org/apache/solr/pkg/TestPackages.java
+++ b/solr/core/src/test/org/apache/solr/pkg/TestPackages.java
@@ -721,6 +721,11 @@ public class TestPackages extends SolrCloudTestCase {
public SolrResponse createResponse(SolrClient client) {
return new SolrResponseBase();
}
+
+ @Override
+ public String getRequestType() {
+ return SolrRequestType.UNSPECIFIED.toString();
+ }
});
verifySchemaComponent(cluster.getSolrClient(), COLLECTION_NAME, "/schema/fieldtypes/myNewTextFieldWithAnalyzerClass",
Utils.makeMap(":fieldType:analyzer:charFilters[0]:_packageinfo_:version" ,"1.0",
diff --git a/solr/core/src/test/org/apache/solr/servlet/TestRequestRateLimiter.java b/solr/core/src/test/org/apache/solr/servlet/TestRequestRateLimiter.java
new file mode 100644
index 00000000000..f7a1fbbc2cb
--- /dev/null
+++ b/solr/core/src/test/org/apache/solr/servlet/TestRequestRateLimiter.java
@@ -0,0 +1,231 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF 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.apache.solr.servlet;
+
+import javax.servlet.FilterConfig;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.concurrent.Callable;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Future;
+import java.util.concurrent.atomic.AtomicInteger;
+
+import org.apache.solr.client.solrj.SolrQuery;
+import org.apache.solr.client.solrj.SolrRequest;
+import org.apache.solr.client.solrj.impl.CloudSolrClient;
+import org.apache.solr.client.solrj.request.CollectionAdminRequest;
+import org.apache.solr.client.solrj.response.QueryResponse;
+import org.apache.solr.cloud.SolrCloudTestCase;
+import org.apache.solr.common.SolrInputDocument;
+import org.apache.solr.common.util.ExecutorUtil;
+import org.junit.BeforeClass;
+import org.junit.Test;
+
+import static org.apache.solr.servlet.RateLimitManager.DEFAULT_SLOT_ACQUISITION_TIMEOUT_MS;
+import static org.hamcrest.CoreMatchers.containsString;
+
+public class TestRequestRateLimiter extends SolrCloudTestCase {
+ private final static String FIRST_COLLECTION = "c1";
+ private final static String SECOND_COLLECTION = "c2";
+
+ @BeforeClass
+ public static void setupCluster() throws Exception {
+ configureCluster(1).addConfig(FIRST_COLLECTION, configset("cloud-minimal")).configure();
+ }
+
+ @Test
+ public void testConcurrentQueries() throws Exception {
+ CloudSolrClient client = cluster.getSolrClient();
+ client.setDefaultCollection(FIRST_COLLECTION);
+
+ CollectionAdminRequest.createCollection(FIRST_COLLECTION, 1, 1).process(client);
+ cluster.waitForActiveCollection(FIRST_COLLECTION, 1, 1);
+
+ SolrDispatchFilter solrDispatchFilter = cluster.getJettySolrRunner(0).getSolrDispatchFilter();
+
+ RequestRateLimiter.RateLimiterConfig rateLimiterConfig = new RequestRateLimiter.RateLimiterConfig(SolrRequest.SolrRequestType.QUERY,
+ true, 1, DEFAULT_SLOT_ACQUISITION_TIMEOUT_MS, 5 /* allowedRequests */, true /* isSlotBorrowing */);
+ // We are fine with a null FilterConfig here since we ensure that MockBuilder never invokes its parent here
+ RateLimitManager.Builder builder = new MockBuilder(null /* dummy FilterConfig */, new MockRequestRateLimiter(rateLimiterConfig, 5));
+ RateLimitManager rateLimitManager = builder.build();
+
+ solrDispatchFilter.replaceRateLimitManager(rateLimitManager);
+
+ processTest(client);
+
+ MockRequestRateLimiter mockQueryRateLimiter = (MockRequestRateLimiter) rateLimitManager.getRequestRateLimiter(SolrRequest.SolrRequestType.QUERY);
+
+ assertEquals(25, mockQueryRateLimiter.incomingRequestCount.get());
+ assertTrue("Incoming accepted new request count did not match. Expected 5 incoming " + mockQueryRateLimiter.acceptedNewRequestCount.get(),
+ mockQueryRateLimiter.acceptedNewRequestCount.get() < 25);
+ assertTrue("Incoming rejected new request count did not match. Expected 20 incoming " + mockQueryRateLimiter.rejectedRequestCount.get(),
+ mockQueryRateLimiter.rejectedRequestCount.get() > 0);
+ assertEquals(mockQueryRateLimiter.incomingRequestCount.get(),
+ mockQueryRateLimiter.acceptedNewRequestCount.get() + mockQueryRateLimiter.rejectedRequestCount.get());
+ }
+
+ @Test
+ public void testSlotBorrowing() throws Exception {
+ CloudSolrClient client = cluster.getSolrClient();
+ client.setDefaultCollection(SECOND_COLLECTION);
+
+ CollectionAdminRequest.createCollection(SECOND_COLLECTION, 1, 1).process(client);
+ cluster.waitForActiveCollection(SECOND_COLLECTION, 1, 1);
+
+ SolrDispatchFilter solrDispatchFilter = cluster.getJettySolrRunner(0).getSolrDispatchFilter();
+
+ RequestRateLimiter.RateLimiterConfig queryRateLimiterConfig = new RequestRateLimiter.RateLimiterConfig(SolrRequest.SolrRequestType.QUERY,
+ true, 1, DEFAULT_SLOT_ACQUISITION_TIMEOUT_MS, 5 /* allowedRequests */, true /* isSlotBorrowing */);
+ RequestRateLimiter.RateLimiterConfig indexRateLimiterConfig = new RequestRateLimiter.RateLimiterConfig(SolrRequest.SolrRequestType.UPDATE,
+ true, 1, DEFAULT_SLOT_ACQUISITION_TIMEOUT_MS, 5 /* allowedRequests */, true /* isSlotBorrowing */);
+ // We are fine with a null FilterConfig here since we ensure that MockBuilder never invokes its parent
+ RateLimitManager.Builder builder = new MockBuilder(null /*dummy FilterConfig */, new MockRequestRateLimiter(queryRateLimiterConfig, 5), new MockRequestRateLimiter(indexRateLimiterConfig, 5));
+ RateLimitManager rateLimitManager = builder.build();
+
+ solrDispatchFilter.replaceRateLimitManager(rateLimitManager);
+
+ processTest(client);
+
+ MockRequestRateLimiter mockIndexRateLimiter = (MockRequestRateLimiter) rateLimitManager.getRequestRateLimiter(SolrRequest.SolrRequestType.UPDATE);
+
+ assertTrue("Incoming slots borrowed count did not match. Expected > 0 incoming " + mockIndexRateLimiter.borrowedSlotCount.get(),
+ mockIndexRateLimiter.borrowedSlotCount.get() > 0);
+ }
+
+ private void processTest(CloudSolrClient client) throws Exception {
+
+ for (int i = 0; i < 100; i++) {
+ SolrInputDocument doc = new SolrInputDocument();
+
+ doc.setField("id", i);
+ doc.setField("text", "foo");
+ client.add(doc);
+ }
+
+ client.commit();
+
+ ExecutorService executor = ExecutorUtil.newMDCAwareCachedThreadPool("threadpool");
+ List<Callable<Boolean>> callableList = new ArrayList<>();
+ List<Future<Boolean>> futures;
+
+ try {
+ for (int i = 0; i < 25; i++) {
+ callableList.add(() -> {
+ try {
+ QueryResponse response = client.query(new SolrQuery("*:*"));
+
+ assertEquals(100, response.getResults().getNumFound());
+ } catch (Exception e) {
+ throw new RuntimeException(e.getMessage());
+ }
+
+ return true;
+ });
+ }
+
+ futures = executor.invokeAll(callableList);
+
+ for (Future<?> future : futures) {
+ try {
+ assertTrue(future.get() != null);
+ } catch (Exception e) {
+ assertThat(e.getMessage(), containsString("non ok status: 429, message:Too Many Requests"));
+ }
+ }
+ } finally {
+ executor.shutdown();
+ }
+ }
+
+ private static class MockRequestRateLimiter extends RequestRateLimiter {
+ final AtomicInteger incomingRequestCount;
+ final AtomicInteger acceptedNewRequestCount;
+ final AtomicInteger rejectedRequestCount;
+ final AtomicInteger borrowedSlotCount;
+
+ private final int maxCount;
+
+ public MockRequestRateLimiter(RateLimiterConfig config, final int maxCount) {
+ super(config);
+
+ this.incomingRequestCount = new AtomicInteger(0);
+ this.acceptedNewRequestCount = new AtomicInteger(0);
+ this.rejectedRequestCount = new AtomicInteger(0);
+ this.borrowedSlotCount = new AtomicInteger(0);
+ this.maxCount = maxCount;
+ }
+
+ @Override
+ public SlotMetadata handleRequest() throws InterruptedException {
+ incomingRequestCount.getAndIncrement();
+
+ SlotMetadata response = super.handleRequest();
+
+ if (response != null) {
+ acceptedNewRequestCount.getAndIncrement();
+ } else {
+ rejectedRequestCount.getAndIncrement();
+ }
+
+ return response;
+ }
+
+ @Override
+ public SlotMetadata allowSlotBorrowing() throws InterruptedException {
+ SlotMetadata result = super.allowSlotBorrowing();
+
+ if (result.isReleasable()) {
+ borrowedSlotCount.incrementAndGet();
+ }
+
+ return result;
+ }
+ }
+
+ private static class MockBuilder extends RateLimitManager.Builder {
+ private final RequestRateLimiter queryRequestRateLimiter;
+ private final RequestRateLimiter indexRequestRateLimiter;
+
+ public MockBuilder(FilterConfig config, RequestRateLimiter queryRequestRateLimiter) {
+ super(config);
+
+ this.queryRequestRateLimiter = queryRequestRateLimiter;
+ this.indexRequestRateLimiter = null;
+ }
+
+ public MockBuilder(FilterConfig config, RequestRateLimiter queryRequestRateLimiter, RequestRateLimiter indexRequestRateLimiter) {
+ super(config);
+
+ this.queryRequestRateLimiter = queryRequestRateLimiter;
+ this.indexRequestRateLimiter = indexRequestRateLimiter;
+ }
+
+ @Override
+ public RateLimitManager build() {
+ RateLimitManager rateLimitManager = new RateLimitManager();
+
+ rateLimitManager.registerRequestRateLimiter(queryRequestRateLimiter, SolrRequest.SolrRequestType.QUERY);
+
+ if (indexRequestRateLimiter != null) {
+ rateLimitManager.registerRequestRateLimiter(indexRequestRateLimiter, SolrRequest.SolrRequestType.UPDATE);
+ }
+
+ return rateLimitManager;
+ }
+ }
+}
diff --git a/solr/solr-ref-guide/src/index.adoc b/solr/solr-ref-guide/src/index.adoc
index 6a750e9acf7..eccd0027643 100644
--- a/solr/solr-ref-guide/src/index.adoc
+++ b/solr/solr-ref-guide/src/index.adoc
@@ -11,6 +11,7 @@
solrcloud, \
legacy-scaling-and-distribution, \
circuit-breakers, \
+ rate-limiters, \
solr-plugins, \
the-well-configured-solr-instance, \
monitoring-solr, \
@@ -124,6 +125,8 @@ The *<<getting-started.adoc#getting-started,Getting Started>>* section guides yo
*<<legacy-scaling-and-distribution.adoc#legacy-scaling-and-distribution,Legacy Scaling and Distribution>>*: This section tells you how to grow a Solr distribution by dividing a large index into sections called shards, which are then distributed across multiple servers, or by replicating a single index across multiple services.
*<<circuit-breakers.adoc#circuit-breakers,Circuit Breakers>>*: This section talks about circuit breakers, a way of allowing a higher stability of Solr nodes and increased service level guarantees of requests that are accepted by Solr.
+
+*<<rate-limiters.adoc#rate-limiters,Request Rate Limiters>>*: This section talks about request rate limiters, a way of guaranteeing throughput per request type and dedicating resource quotas by resource type. Rate limiter configurations are per instance/JVM and applied to the entire JVM, not at a core/collection level.
****
.Advanced Configuration
diff --git a/solr/solr-ref-guide/src/rate-limiters.adoc b/solr/solr-ref-guide/src/rate-limiters.adoc
new file mode 100644
index 00000000000..d01153d5d92
--- /dev/null
+++ b/solr/solr-ref-guide/src/rate-limiters.adoc
@@ -0,0 +1,128 @@
+= Request Rate Limiters
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF 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.
+
+Solr allows rate limiting per request type. Each request type can be allocated a maximum allowed number of concurrent requests
+that can be active. The default rate limiting is implemented for updates and searches.
+
+If a request exceeds the request quota, further incoming requests are rejected with HTTP error code 429 (Too Many Requests).
+
+Note that rate limiting works at an instance (JVM) level, not at a core or collection level. Consider that when planning capacity.
+There is a future work planned to have finer grained execution here (https://issues.apache.org/jira/browse/SOLR-14710).
+
+== When To Use Rate Limiters
+Rate limiters should be used when the user wishes to allocate a guaranteed capacity of the request threadpool to a specific
+request type. Indexing and search requests are mostly competing with each other for CPU resources. This becomes especially
+pronounced under high stress in production workloads. The current implementation has a query rate limiter which can free up
+resources for indexing.
+
+== Rate Limiter Configurations
+The default rate limiter is search rate limiter. Accordingly, it can be configured in web.xml under initParams for
+SolrRequestFilter.
+
+[source,xml]
+----
+<filter-name>SolrRequestFilter</filter-name>
+----
+
+==== Enable Query Rate Limiter
+Controls enabling of query rate limiter. Default value is false.
+[source,xml]
+----
+<param-name>isQueryRateLimiterEnabled</param-name>
+----
+[source,xml]
+----
+<param-value>true</param-value>
+----
+
+==== Maximum Number Of Concurrent Requests
+Allows setting maximum concurrent search requests at a given point in time. Default value is number of cores * 3.
+[source,xml]
+----
+<param-name>maxQueryRequests</param-name>
+----
+[source,xml]
+----
+<param-value>15</param-value>
+----
+
+==== Request Slot Allocation Wait Time
+Wait time in ms for which a request will wait for a slot to be available when all slots are full,
+before the request is put into the wait queue. This allows requests to have a chance to proceed if
+the unavailability of the request slots for this rate limiter is a transient phenomenon. Default value
+is -1, indicating no wait. 0 will represent the same -- no wait. Note that higher request allocation times
+can lead to larger queue times and can potentially lead to longer wait times for queries.
+[source,xml]
+----
+<param-name>queryWaitForSlotAllocationInMS</param-name>
+----
+[source,xml]
+----
+<param-value>100</param-value>
+----
+
+==== Slot Borrowing Enabled
+If slot borrowing (described below) is enabled or not. Default value is false.
+
+NOTE: This feature is experimental and can cause slots to be blocked if the
+borrowing request is long lived.
+[source,xml]
+----
+<param-name>queryAllowSlotBorrowing</param-name>
+----
+[source,xml]
+----
+<param-value>true</param-value>
+----
+
+==== Guaranteed Slots
+The number of guaranteed slots that the query rate limiter will reserve irrespective
+of the load of query requests. This is used only if slot borrowing is enabled and acts
+as the threshold beyond which query rate limiter will not allow other request types to
+borrow slots from its quota. Default value is allowed number of concurrent requests / 2.
+
+NOTE: This feature is experimental and can cause slots to be blocked if the
+borrowing request is long lived.
+[source,xml]
+----
+<param-name>queryGuaranteedSlots</param-name>
+----
+[source,xml]
+----
+<param-value>200</param-value>
+----
+
+== Salient Points
+
+These are some of the things to keep in mind when using rate limiters
+
+=== Over Subscribing
+It is possible to define a size of quota for a request type which exceeds the size
+of the available threadpool. Solr does not enforce rules on the size of a quota that
+can be define for a request type. This is intentionally done to allow users full
+control on their quota allocation. However, if the quota exceeds the available threadpool's
+size, the standard queuing policies of the threadpool will kick in.
+
+=== Slot Borrowing
+If a quota does not have backlog but other quotas do, then the relatively less busier quota can
+"borrow" slot from the busier quotas. This is done on a round robin basis today with a futuristic
+pending task to make it a priority based model (https://issues.apache.org/jira/browse/SOLR-14709).
+
+NOTE: This feature is experimental and gives no guarantee of borrowed slots being
+returned in time.
+
diff --git a/solr/solrj/src/java/org/apache/solr/client/solrj/SolrClient.java b/solr/solrj/src/java/org/apache/solr/client/solrj/SolrClient.java
index 01f57756423..cee4e9a9c8a 100644
--- a/solr/solrj/src/java/org/apache/solr/client/solrj/SolrClient.java
+++ b/solr/solrj/src/java/org/apache/solr/client/solrj/SolrClient.java
@@ -1305,4 +1305,12 @@ public abstract class SolrClient implements Serializable, Closeable {
return binder;
}
+ /**
+ * This method defines the context in which this Solr client
+ * is being used (e.g. for internal communication between Solr
+ * nodes or as an external client). The default value is {@code SolrClientContext#Client}
+ */
+ public SolrRequest.SolrClientContext getContext() {
+ return SolrRequest.SolrClientContext.CLIENT;
+ }
}
diff --git a/solr/solrj/src/java/org/apache/solr/client/solrj/SolrRequest.java b/solr/solrj/src/java/org/apache/solr/client/solrj/SolrRequest.java
index 31dcda09217..22e615f9237 100644
--- a/solr/solrj/src/java/org/apache/solr/client/solrj/SolrRequest.java
+++ b/solr/solrj/src/java/org/apache/solr/client/solrj/SolrRequest.java
@@ -54,6 +54,20 @@ public abstract class SolrRequest<T extends SolrResponse> implements Serializabl
DELETE
};
+ public enum SolrRequestType {
+ QUERY,
+ UPDATE,
+ SECURITY,
+ ADMIN,
+ STREAMING,
+ UNSPECIFIED
+ };
+
+ public enum SolrClientContext {
+ CLIENT,
+ SERVER
+ };
+
public static final Set<String> SUPPORTED_METHODS = Set.of(
METHOD.GET.toString(),
METHOD.POST.toString(),
@@ -168,6 +182,11 @@ public abstract class SolrRequest<T extends SolrResponse> implements Serializabl
this.queryParams = queryParams;
}
+ /**
+ * This method defines the type of this Solr request.
+ */
+ public abstract String getRequestType();
+
public abstract SolrParams getParams();
/**
diff --git a/solr/solrj/src/java/org/apache/solr/client/solrj/impl/HttpSolrClient.java b/solr/solrj/src/java/org/apache/solr/client/solrj/impl/HttpSolrClient.java
index 78106295e19..e95c5d0d315 100644
--- a/solr/solrj/src/java/org/apache/solr/client/solrj/impl/HttpSolrClient.java
+++ b/solr/solrj/src/java/org/apache/solr/client/solrj/impl/HttpSolrClient.java
@@ -44,6 +44,7 @@ import java.util.concurrent.Future;
import org.apache.commons.io.IOUtils;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
+import org.apache.http.HttpMessage;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
@@ -98,6 +99,8 @@ public class HttpSolrClient extends BaseHttpSolrClient {
private static final Charset FALLBACK_CHARSET = StandardCharsets.UTF_8;
private static final String DEFAULT_PATH = "/select";
private static final long serialVersionUID = -946812319974801896L;
+
+ protected static final Set<Integer> UNMATCHED_ACCEPTED_ERROR_CODES = Collections.singleton(429);
/**
* User-Agent String.
@@ -358,7 +361,9 @@ public class HttpSolrClient extends BaseHttpSolrClient {
if (parser == null) {
parser = this.parser;
}
-
+
+ Header[] contextHeaders = buildRequestSpecificHeaders(request);
+
// The parser 'wt=' and 'version=' params are used instead of the original
// params
ModifiableSolrParams wparams = new ModifiableSolrParams(params);
@@ -387,7 +392,10 @@ public class HttpSolrClient extends BaseHttpSolrClient {
throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "GET can't send streams!");
}
- return new HttpGet(basePath + path + wparams.toQueryString());
+ HttpGet result = new HttpGet(basePath + path + wparams.toQueryString());
+
+ populateHeaders(result, contextHeaders);
+ return result;
}
if (SolrRequest.METHOD.DELETE == request.getMethod()) {
@@ -428,6 +436,9 @@ public class HttpSolrClient extends BaseHttpSolrClient {
contentWriter.write(outstream);
}
});
+
+ populateHeaders(postOrPut, contextHeaders);
+
return postOrPut;
} else if (streams == null || isMultipart) {
@@ -624,6 +635,12 @@ public class HttpSolrClient extends BaseHttpSolrClient {
if (procCt != null) {
String procMimeType = ContentType.parse(procCt).getMimeType().trim().toLowerCase(Locale.ROOT);
if (!procMimeType.equals(mimeType)) {
+ if (isUnmatchedErrorCode(mimeType, httpStatus)) {
+ throw new RemoteSolrException(baseUrl, httpStatus, "non ok status: " + httpStatus
+ + ", message:" + response.getStatusLine().getReasonPhrase(),
+ null);
+ }
+
// unexpected mime type
String msg = "Expected mime type " + procMimeType + " but got " + mimeType + ".";
Charset exceptionCharset = charset != null? charset : FALLBACK_CHARSET;
@@ -699,6 +716,37 @@ public class HttpSolrClient extends BaseHttpSolrClient {
}
}
}
+
+ // When raising an error using HTTP sendError, mime types can be mismatched. This is specifically true when
+ // SolrDispatchFilter uses the sendError mechanism since the expected MIME type of response is not HTML but
+ // HTTP sendError generates a HTML output, which can lead to mismatch
+ private boolean isUnmatchedErrorCode(String mimeType, int httpStatus) {
+ if (mimeType == null) {
+ return false;
+ }
+
+ if (mimeType.equalsIgnoreCase("text/html") && UNMATCHED_ACCEPTED_ERROR_CODES.contains(httpStatus)) {
+ return true;
+ }
+
+ return false;
+ }
+
+ private Header[] buildRequestSpecificHeaders(@SuppressWarnings({"rawtypes"}) final SolrRequest request) {
+ Header[] contextHeaders = new Header[2];
+
+ //TODO: validate request context here: https://issues.apache.org/jira/browse/SOLR-14720
+ contextHeaders[0] = new BasicHeader(CommonParams.SOLR_REQUEST_CONTEXT_PARAM, getContext().toString());
+
+ contextHeaders[1] = new BasicHeader(CommonParams.SOLR_REQUEST_TYPE_PARAM, request.getRequestType());
+
+ return contextHeaders;
+ }
+
+ private void populateHeaders(HttpMessage message, Header[] contextHeaders) {
+ message.addHeader(contextHeaders[0]);
+ message.addHeader(contextHeaders[1]);
+ }
// -------------------------------------------------------------------
// -------------------------------------------------------------------
diff --git a/solr/solrj/src/java/org/apache/solr/client/solrj/request/AbstractUpdateRequest.java b/solr/solrj/src/java/org/apache/solr/client/solrj/request/AbstractUpdateRequest.java
index cb9e74e81c2..2b9870d6a2e 100644
--- a/solr/solrj/src/java/org/apache/solr/client/solrj/request/AbstractUpdateRequest.java
+++ b/solr/solrj/src/java/org/apache/solr/client/solrj/request/AbstractUpdateRequest.java
@@ -116,6 +116,11 @@ public abstract class AbstractUpdateRequest extends SolrRequest<UpdateResponse>
return new UpdateResponse();
}
+ @Override
+ public String getRequestType() {
+ return SolrRequestType.UPDATE.toString();
+ }
+
public boolean isWaitSearcher() {
return params != null && params.getBool(UpdateParams.WAIT_SEARCHER, false);
}
diff --git a/solr/solrj/src/java/org/apache/solr/client/solrj/request/CollectionAdminRequest.java b/solr/solrj/src/java/org/apache/solr/client/solrj/request/CollectionAdminRequest.java
index e0955c2fe31..bffdc4e13f3 100644
--- a/solr/solrj/src/java/org/apache/solr/client/solrj/request/CollectionAdminRequest.java
+++ b/solr/solrj/src/java/org/apache/solr/client/solrj/request/CollectionAdminRequest.java
@@ -146,6 +146,11 @@ public abstract class CollectionAdminRequest<T extends CollectionAdminResponse>
return jsonStr();
}
+ @Override
+ public String getRequestType() {
+ return SolrRequestType.ADMIN.toString();
+ }
+
/**
* Base class for asynchronous collection admin requests
*/
diff --git a/solr/solrj/src/java/org/apache/solr/client/solrj/request/ConfigSetAdminRequest.java b/solr/solrj/src/java/org/apache/solr/client/solrj/request/ConfigSetAdminRequest.java
index ab06a9f5501..e171aa12851 100644
--- a/solr/solrj/src/java/org/apache/solr/client/solrj/request/ConfigSetAdminRequest.java
+++ b/solr/solrj/src/java/org/apache/solr/client/solrj/request/ConfigSetAdminRequest.java
@@ -100,6 +100,11 @@ public abstract class ConfigSetAdminRequest
}
}
+ @Override
+ public String getRequestType() {
+ return SolrRequestType.ADMIN.toString();
+ }
+
// CREATE request
public static class Create extends ConfigSetSpecificAdminRequest<Create> {
protected static String PROPERTY_PREFIX = "configSetProp";
diff --git a/solr/solrj/src/java/org/apache/solr/client/solrj/request/CoreAdminRequest.java b/solr/solrj/src/java/org/apache/solr/client/solrj/request/CoreAdminRequest.java
index 692b54d3e69..9e571b7bb07 100644
--- a/solr/solrj/src/java/org/apache/solr/client/solrj/request/CoreAdminRequest.java
+++ b/solr/solrj/src/java/org/apache/solr/client/solrj/request/CoreAdminRequest.java
@@ -43,6 +43,11 @@ public class CoreAdminRequest extends SolrRequest<CoreAdminResponse> {
protected String other = null;
protected boolean isIndexInfoNeeded = true;
protected CoreAdminParams.CoreAdminAction action = null;
+
+ @Override
+ public String getRequestType() {
+ return SolrRequestType.ADMIN.toString();
+ }
//a create core request
public static class Create extends CoreAdminRequest {
diff --git a/solr/solrj/src/java/org/apache/solr/client/solrj/request/DelegationTokenRequest.java b/solr/solrj/src/java/org/apache/solr/client/solrj/request/DelegationTokenRequest.java
index 697a6ada342..160ae3cec51 100644
--- a/solr/solrj/src/java/org/apache/solr/client/solrj/request/DelegationTokenRequest.java
+++ b/solr/solrj/src/java/org/apache/solr/client/solrj/request/DelegationTokenRequest.java
@@ -81,6 +81,11 @@ public abstract class DelegationTokenRequest
@Override
public DelegationTokenResponse.Get createResponse(SolrClient client) { return new DelegationTokenResponse.Get(); }
+
+ @Override
+ public String getRequestType() {
+ return SolrRequestType.ADMIN.toString();
+ }
}
public static class Renew extends DelegationTokenRequest<Renew, DelegationTokenResponse.Renew> {
@@ -108,6 +113,11 @@ public abstract class DelegationTokenRequest
@Override
public DelegationTokenResponse.Renew createResponse(SolrClient client) { return new DelegationTokenResponse.Renew(); }
+
+ @Override
+ public String getRequestType() {
+ return SolrRequestType.ADMIN.toString();
+ }
}
public static class Cancel extends DelegationTokenRequest<Cancel, DelegationTokenResponse.Cancel> {
@@ -136,5 +146,10 @@ public abstract class DelegationTokenRequest
@Override
public DelegationTokenResponse.Cancel createResponse(SolrClient client) { return new DelegationTokenResponse.Cancel(); }
+
+ @Override
+ public String getRequestType() {
+ return SolrRequestType.ADMIN.toString();
+ }
}
}
diff --git a/solr/solrj/src/java/org/apache/solr/client/solrj/request/DirectXmlRequest.java b/solr/solrj/src/java/org/apache/solr/client/solrj/request/DirectXmlRequest.java
index ef5e9544d81..6d0d3285681 100644
--- a/solr/solrj/src/java/org/apache/solr/client/solrj/request/DirectXmlRequest.java
+++ b/solr/solrj/src/java/org/apache/solr/client/solrj/request/DirectXmlRequest.java
@@ -54,6 +54,11 @@ public class DirectXmlRequest extends SolrRequest<UpdateResponse> implements IsU
return params;
}
+ @Override
+ public String getRequestType() {
+ return SolrRequestType.UPDATE.toString();
+ }
+
public void setParams(SolrParams params) {
this.params = params;
diff --git a/solr/solrj/src/java/org/apache/solr/client/solrj/request/DocumentAnalysisRequest.java b/solr/solrj/src/java/org/apache/solr/client/solrj/request/DocumentAnalysisRequest.java
index be985e1eae8..09263be00f0 100644
--- a/solr/solrj/src/java/org/apache/solr/client/solrj/request/DocumentAnalysisRequest.java
+++ b/solr/solrj/src/java/org/apache/solr/client/solrj/request/DocumentAnalysisRequest.java
@@ -209,4 +209,9 @@ public class DocumentAnalysisRequest extends SolrRequest<DocumentAnalysisRespons
return showMatch;
}
+ @Override
+ public String getRequestType() {
+ return SolrRequestType.QUERY.toString();
+ }
+
}
diff --git a/solr/solrj/src/java/org/apache/solr/client/solrj/request/FieldAnalysisRequest.java b/solr/solrj/src/java/org/apache/solr/client/solrj/request/FieldAnalysisRequest.java
index aeea9e04c72..7ca681216b6 100644
--- a/solr/solrj/src/java/org/apache/solr/client/solrj/request/FieldAnalysisRequest.java
+++ b/solr/solrj/src/java/org/apache/solr/client/solrj/request/FieldAnalysisRequest.java
@@ -87,6 +87,11 @@ public class FieldAnalysisRequest extends SolrRequest<FieldAnalysisResponse> {
return params;
}
+ @Override
+ public String getRequestType() {
+ return SolrRequestType.QUERY.toString();
+ }
+
//================================================ Helper Methods ==================================================
/**
diff --git a/solr/solrj/src/java/org/apache/solr/client/solrj/request/GenericSolrRequest.java b/solr/solrj/src/java/org/apache/solr/client/solrj/request/GenericSolrRequest.java
index d87892521a9..27eb410496b 100644
--- a/solr/solrj/src/java/org/apache/solr/client/solrj/request/GenericSolrRequest.java
+++ b/solr/solrj/src/java/org/apache/solr/client/solrj/request/GenericSolrRequest.java
@@ -51,4 +51,9 @@ public class GenericSolrRequest extends SolrRequest<SimpleSolrResponse> {
protected SimpleSolrResponse createResponse(SolrClient client) {
return response;
}
+
+ @Override
+ public String getRequestType() {
+ return SolrRequestType.UNSPECIFIED.toString();
+ }
}
diff --git a/solr/solrj/src/java/org/apache/solr/client/solrj/request/HealthCheckRequest.java b/solr/solrj/src/java/org/apache/solr/client/solrj/request/HealthCheckRequest.java
index 50d4d8cbae3..f3aeb402629 100644
--- a/solr/solrj/src/java/org/apache/solr/client/solrj/request/HealthCheckRequest.java
+++ b/solr/solrj/src/java/org/apache/solr/client/solrj/request/HealthCheckRequest.java
@@ -48,5 +48,8 @@ public class HealthCheckRequest extends SolrRequest<HealthCheckResponse> {
return new HealthCheckResponse();
}
-
+ @Override
+ public String getRequestType() {
+ return SolrRequestType.ADMIN.toString();
+ }
}
diff --git a/solr/solrj/src/java/org/apache/solr/client/solrj/request/LukeRequest.java b/solr/solrj/src/java/org/apache/solr/client/solrj/request/LukeRequest.java
index 6e89c8470ab..a43b4a94832 100644
--- a/solr/solrj/src/java/org/apache/solr/client/solrj/request/LukeRequest.java
+++ b/solr/solrj/src/java/org/apache/solr/client/solrj/request/LukeRequest.java
@@ -129,5 +129,10 @@ public class LukeRequest extends SolrRequest<LukeResponse> {
return params;
}
+ @Override
+ public String getRequestType() {
+ return SolrRequestType.ADMIN.toString();
+ }
+
}
diff --git a/solr/solrj/src/java/org/apache/solr/client/solrj/request/QueryRequest.java b/solr/solrj/src/java/org/apache/solr/client/solrj/request/QueryRequest.java
index 1c2fda4f594..d80ab646155 100644
--- a/solr/solrj/src/java/org/apache/solr/client/solrj/request/QueryRequest.java
+++ b/solr/solrj/src/java/org/apache/solr/client/solrj/request/QueryRequest.java
@@ -76,5 +76,9 @@ public class QueryRequest extends SolrRequest<QueryResponse> {
return query;
}
+ @Override
+ public String getRequestType() {
+ return SolrRequestType.QUERY.toString();
+ }
}
diff --git a/solr/solrj/src/java/org/apache/solr/client/solrj/request/SolrPing.java b/solr/solrj/src/java/org/apache/solr/client/solrj/request/SolrPing.java
index 43801c61d43..75cfb52c33d 100644
--- a/solr/solrj/src/java/org/apache/solr/client/solrj/request/SolrPing.java
+++ b/solr/solrj/src/java/org/apache/solr/client/solrj/request/SolrPing.java
@@ -54,6 +54,11 @@ public class SolrPing extends SolrRequest<SolrPingResponse> {
public ModifiableSolrParams getParams() {
return params;
}
+
+ @Override
+ public String getRequestType() {
+ return SolrRequestType.ADMIN.toString();
+ }
/**
* Remove the action parameter from this request. This will result in the same
diff --git a/solr/solrj/src/java/org/apache/solr/client/solrj/request/V2Request.java b/solr/solrj/src/java/org/apache/solr/client/solrj/request/V2Request.java
index 5334edd3877..932eb6bdd5b 100644
--- a/solr/solrj/src/java/org/apache/solr/client/solrj/request/V2Request.java
+++ b/solr/solrj/src/java/org/apache/solr/client/solrj/request/V2Request.java
@@ -133,6 +133,11 @@ public class V2Request extends SolrRequest<V2Response> implements MapWriter {
return super.getResponseParser();
}
+ @Override
+ public String getRequestType() {
+ return SolrRequestType.ADMIN.toString();
+ }
+
public static class Builder {
private String resource;
private METHOD method = METHOD.GET;
diff --git a/solr/solrj/src/java/org/apache/solr/client/solrj/request/schema/AbstractSchemaRequest.java b/solr/solrj/src/java/org/apache/solr/client/solrj/request/schema/AbstractSchemaRequest.java
index b20a570c42e..ed0f315b959 100644
--- a/solr/solrj/src/java/org/apache/solr/client/solrj/request/schema/AbstractSchemaRequest.java
+++ b/solr/solrj/src/java/org/apache/solr/client/solrj/request/schema/AbstractSchemaRequest.java
@@ -37,4 +37,8 @@ public abstract class AbstractSchemaRequest<T extends SolrResponse> extends Solr
return params;
}
+ @Override
+ public String getRequestType() {
+ return SolrRequestType.ADMIN.toString();
+ }
}
diff --git a/solr/solrj/src/java/org/apache/solr/common/SolrException.java b/solr/solrj/src/java/org/apache/solr/common/SolrException.java
index 9909c2b719c..2375710e13f 100644
--- a/solr/solrj/src/java/org/apache/solr/common/SolrException.java
+++ b/solr/solrj/src/java/org/apache/solr/common/SolrException.java
@@ -48,6 +48,7 @@ public class SolrException extends RuntimeException {
NOT_FOUND( 404 ),
CONFLICT( 409 ),
UNSUPPORTED_MEDIA_TYPE( 415 ),
+ TOO_MANY_REQUESTS(429),
SERVER_ERROR( 500 ),
SERVICE_UNAVAILABLE( 503 ),
INVALID_STATE( 510 ),
diff --git a/solr/solrj/src/java/org/apache/solr/common/params/CommonParams.java b/solr/solrj/src/java/org/apache/solr/common/params/CommonParams.java
index 6f1d4e8783b..a78faceb553 100644
--- a/solr/solrj/src/java/org/apache/solr/common/params/CommonParams.java
+++ b/solr/solrj/src/java/org/apache/solr/common/params/CommonParams.java
@@ -294,6 +294,10 @@ public interface CommonParams {
String NAME = "name";
String VALUE_LONG = "val";
+ String SOLR_REQUEST_CONTEXT_PARAM = "Solr-Request-Context";
+
+ String SOLR_REQUEST_TYPE_PARAM = "Solr-Request-Type";
+
String VERSION_FIELD="_version_";
String FAIL_ON_VERSION_CONFLICTS ="failOnVersionConflicts";
diff --git a/solr/test-framework/src/java/org/apache/solr/cloud/ConfigRequest.java b/solr/test-framework/src/java/org/apache/solr/cloud/ConfigRequest.java
index 6b4c61770d0..45f7604bbfd 100644
--- a/solr/test-framework/src/java/org/apache/solr/cloud/ConfigRequest.java
+++ b/solr/test-framework/src/java/org/apache/solr/cloud/ConfigRequest.java
@@ -53,4 +53,9 @@ public class ConfigRequest extends SolrRequest {
public SolrResponse createResponse(SolrClient client) {
return new SolrResponseBase();
}
+
+ @Override
+ public String getRequestType() {
+ return SolrRequest.SolrRequestType.ADMIN.toString();
+ }
}