madrob commented on a change in pull request #1686: URL: https://github.com/apache/lucene-solr/pull/1686#discussion_r465207154
########## File path: solr/core/src/java/org/apache/solr/servlet/SolrDispatchFilter.java ########## @@ -377,6 +386,19 @@ public void doFilter(ServletRequest _request, ServletResponse _response, FilterC } } + try { + accepted = rateLimitManager.handleRequest(request); + } catch (InterruptedException e) { + throw new SolrException(ErrorCode.SERVER_ERROR, e.getMessage()); Review comment: Thread.currentThread.interrupt ########## File path: solr/core/src/java/org/apache/solr/servlet/RateLimitManager.java ########## @@ -0,0 +1,148 @@ +/* + * 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.util.HashMap; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +import org.apache.solr.client.solrj.SolrRequest; + +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. + */ +public class RateLimitManager { + 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> 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; + } + + if (requestRateLimiter.handleRequest()) { + activeRequestsMap.put(request, requestRateLimiter); + return true; + } + + requestRateLimiter = trySlotBorrowing(typeOfRequest); + + if (requestRateLimiter != null) { + activeRequestsMap.put(request, requestRateLimiter); + 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. + */ + private RequestRateLimiter trySlotBorrowing(String requestType) { + for (Map.Entry<String, RequestRateLimiter> currentEntry : requestRateLimiterMap.entrySet()) { + RequestRateLimiter requestRateLimiter = currentEntry.getValue(); + + if (requestRateLimiter.getRateLimiterConfig().requestType.equals(requestType)) { Review comment: This is always false due to type mismatch. ########## File path: solr/core/src/test/org/apache/solr/servlet/TestRequestRateLimiter.java ########## @@ -0,0 +1,185 @@ +/* + * 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 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; + +public class TestRequestRateLimiter extends SolrCloudTestCase { + private final static String COLLECTION = "c1"; + + @BeforeClass + public static void setupCluster() throws Exception { + configureCluster(1).addConfig(COLLECTION, configset("cloud-minimal")).configure(); + } + + @Test + public void testConcurrentQueries() throws Exception { + CloudSolrClient client = cluster.getSolrClient(); + client.setDefaultCollection(COLLECTION); + + CollectionAdminRequest.createCollection(COLLECTION, 1, 1).process(client); + cluster.waitForActiveCollection(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 */); + RateLimitManager.Builder builder = new MockBuilder(new MockRequestRateLimiter(rateLimiterConfig, 5)); + RateLimitManager rateLimitManager = builder.build(); + + solrDispatchFilter.replaceRateLimitManager(rateLimitManager); + + 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(new Callable<Boolean>() { Review comment: nit: use a lambda? ########## File path: solr/core/src/java/org/apache/solr/servlet/SolrDispatchFilter.java ########## @@ -184,6 +187,11 @@ public void init(FilterConfig config) throws ServletException coresInit = createCoreContainer(solrHomePath, extraProperties); this.httpClient = coresInit.getUpdateShardHandler().getDefaultHttpClient(); setupJvmMetrics(coresInit); + RateLimitManager.Builder builder = new RateLimitManager.Builder(); + + builder.setConfig(config); Review comment: This is required, make it a constructor parameter on the builder? ########## File path: solr/core/src/test/org/apache/solr/servlet/TestRequestRateLimiter.java ########## @@ -0,0 +1,185 @@ +/* + * 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 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; + +public class TestRequestRateLimiter extends SolrCloudTestCase { + private final static String COLLECTION = "c1"; + + @BeforeClass + public static void setupCluster() throws Exception { + configureCluster(1).addConfig(COLLECTION, configset("cloud-minimal")).configure(); + } + + @Test + public void testConcurrentQueries() throws Exception { + CloudSolrClient client = cluster.getSolrClient(); + client.setDefaultCollection(COLLECTION); + + CollectionAdminRequest.createCollection(COLLECTION, 1, 1).process(client); + cluster.waitForActiveCollection(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 */); + RateLimitManager.Builder builder = new MockBuilder(new MockRequestRateLimiter(rateLimiterConfig, 5)); + RateLimitManager rateLimitManager = builder.build(); + + solrDispatchFilter.replaceRateLimitManager(rateLimitManager); + + 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(new Callable<Boolean>() { + @Override + public Boolean call() throws Exception { + try { + QueryResponse response = client.query(new SolrQuery("*:*")); + + if (response.getResults().getNumFound() > 0) { + assertEquals(100, response.getResults().getNumFound()); + } + } catch (Exception e) { + throw new RuntimeException(e.getMessage()); + } + + return true; + } + }); + } + + futures = executor.invokeAll(callableList); + + for (Future<?> future : futures) { + try { + future.get(); + } catch (Exception e) { + assertTrue("Not true " + e.getMessage(), e.getMessage().contains("non ok status: 429, message:Too Many Requests")); Review comment: assertThat(e.getMessage(), contains(...)) ########## File path: solr/core/src/test/org/apache/solr/servlet/TestRequestRateLimiter.java ########## @@ -0,0 +1,185 @@ +/* + * 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 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; + +public class TestRequestRateLimiter extends SolrCloudTestCase { Review comment: I'd like to see some testing around the slot borrowing? ########## File path: solr/core/src/java/org/apache/solr/servlet/RateLimitManager.java ########## @@ -0,0 +1,148 @@ +/* + * 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.util.HashMap; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +import org.apache.solr.client.solrj.SolrRequest; + +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. + */ +public class RateLimitManager { + 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> 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; + } + + if (requestRateLimiter.handleRequest()) { + activeRequestsMap.put(request, requestRateLimiter); + return true; + } + + requestRateLimiter = trySlotBorrowing(typeOfRequest); + + if (requestRateLimiter != null) { Review comment: do we need a call to `handleRequest` here? ########## File path: solr/core/src/java/org/apache/solr/servlet/RateLimitManager.java ########## @@ -0,0 +1,148 @@ +/* + * 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.util.HashMap; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +import org.apache.solr.client.solrj.SolrRequest; + +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. + */ +public class RateLimitManager { + 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> activeRequestsMap; Review comment: Please add some comments here clarifying that callers must acquire the semaphore lease before adding requests to the map (and must delete from the map before returning the lease). ########## File path: solr/core/src/java/org/apache/solr/servlet/RateLimitManager.java ########## @@ -0,0 +1,148 @@ +/* + * 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.util.HashMap; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +import org.apache.solr.client.solrj.SolrRequest; + +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. + */ +public class RateLimitManager { + 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> 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; + } + + if (requestRateLimiter.handleRequest()) { + activeRequestsMap.put(request, requestRateLimiter); + return true; + } + + requestRateLimiter = trySlotBorrowing(typeOfRequest); + + if (requestRateLimiter != null) { + activeRequestsMap.put(request, requestRateLimiter); + 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. + */ + private RequestRateLimiter trySlotBorrowing(String requestType) { + for (Map.Entry<String, RequestRateLimiter> currentEntry : requestRateLimiterMap.entrySet()) { + RequestRateLimiter requestRateLimiter = currentEntry.getValue(); + + if (requestRateLimiter.getRateLimiterConfig().requestType.equals(requestType)) { + continue; + } + + if (requestRateLimiter.getRateLimiterConfig().isSlotBorrowingEnabled && requestRateLimiter.allowSlotBorrowing()) { + return requestRateLimiter; + } + } + + return null; + } + + // Decrement the active requests in the rate limiter for the corresponding request type. + public void decrementActiveRequests(HttpServletRequest request) { + RequestRateLimiter requestRateLimiter = activeRequestsMap.get(request); + + if (requestRateLimiter == null) { + // No rate limiter for this request type + return; + } + + requestRateLimiter.decrementConcurrentRequests(); + activeRequestsMap.remove(request); Review comment: Potential deadlock - reorder this. Possibly consider using `computeIfPresent`. ########## File path: solr/core/src/java/org/apache/solr/servlet/RateLimitManager.java ########## @@ -0,0 +1,148 @@ +/* + * 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.util.HashMap; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +import org.apache.solr.client.solrj.SolrRequest; + +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. + */ +public class RateLimitManager { + 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> 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; + } + + if (requestRateLimiter.handleRequest()) { + activeRequestsMap.put(request, requestRateLimiter); + return true; + } + + requestRateLimiter = trySlotBorrowing(typeOfRequest); + + if (requestRateLimiter != null) { + activeRequestsMap.put(request, requestRateLimiter); + 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. + */ + private RequestRateLimiter trySlotBorrowing(String requestType) { + for (Map.Entry<String, RequestRateLimiter> currentEntry : requestRateLimiterMap.entrySet()) { + RequestRateLimiter requestRateLimiter = currentEntry.getValue(); + + if (requestRateLimiter.getRateLimiterConfig().requestType.equals(requestType)) { + continue; + } + + if (requestRateLimiter.getRateLimiterConfig().isSlotBorrowingEnabled && requestRateLimiter.allowSlotBorrowing()) { + return requestRateLimiter; + } + } + + return null; + } + + // Decrement the active requests in the rate limiter for the corresponding request type. + public void decrementActiveRequests(HttpServletRequest request) { Review comment: I feel like this is insufficient. If this request is part of its own queue, but there is another request of this same type that is currently borrowing a slot from another queue, then we shout prioritize returning the borrowed slot instead of our own. This might have potential performance implications and can lead to livelock/request starvation. ########## File path: solr/core/src/test/org/apache/solr/servlet/TestRequestRateLimiter.java ########## @@ -0,0 +1,185 @@ +/* + * 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 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; + +public class TestRequestRateLimiter extends SolrCloudTestCase { + private final static String COLLECTION = "c1"; + + @BeforeClass + public static void setupCluster() throws Exception { + configureCluster(1).addConfig(COLLECTION, configset("cloud-minimal")).configure(); + } + + @Test + public void testConcurrentQueries() throws Exception { + CloudSolrClient client = cluster.getSolrClient(); + client.setDefaultCollection(COLLECTION); + + CollectionAdminRequest.createCollection(COLLECTION, 1, 1).process(client); + cluster.waitForActiveCollection(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 */); + RateLimitManager.Builder builder = new MockBuilder(new MockRequestRateLimiter(rateLimiterConfig, 5)); + RateLimitManager rateLimitManager = builder.build(); + + solrDispatchFilter.replaceRateLimitManager(rateLimitManager); + + 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(new Callable<Boolean>() { + @Override + public Boolean call() throws Exception { + try { + QueryResponse response = client.query(new SolrQuery("*:*")); + + if (response.getResults().getNumFound() > 0) { + assertEquals(100, response.getResults().getNumFound()); + } + } catch (Exception e) { + throw new RuntimeException(e.getMessage()); + } + + return true; + } + }); + } + + futures = executor.invokeAll(callableList); + + for (Future<?> future : futures) { + try { + future.get(); + } catch (Exception e) { + assertTrue("Not true " + e.getMessage(), e.getMessage().contains("non ok status: 429, message:Too Many Requests")); + } + } + + MockRequestRateLimiter mockQueryRateLimiter = (MockRequestRateLimiter) rateLimitManager.getRequestRateLimiter(SolrRequest.SolrRequestType.QUERY); + + assertTrue("Incoming request count did not match. Expected == 25 incoming " + mockQueryRateLimiter.incomingRequestCount.get(), Review comment: assertEquals ########## File path: solr/core/src/test/org/apache/solr/servlet/TestRequestRateLimiter.java ########## @@ -0,0 +1,185 @@ +/* + * 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 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; + +public class TestRequestRateLimiter extends SolrCloudTestCase { + private final static String COLLECTION = "c1"; + + @BeforeClass + public static void setupCluster() throws Exception { + configureCluster(1).addConfig(COLLECTION, configset("cloud-minimal")).configure(); + } + + @Test + public void testConcurrentQueries() throws Exception { + CloudSolrClient client = cluster.getSolrClient(); + client.setDefaultCollection(COLLECTION); + + CollectionAdminRequest.createCollection(COLLECTION, 1, 1).process(client); + cluster.waitForActiveCollection(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 */); + RateLimitManager.Builder builder = new MockBuilder(new MockRequestRateLimiter(rateLimiterConfig, 5)); + RateLimitManager rateLimitManager = builder.build(); + + solrDispatchFilter.replaceRateLimitManager(rateLimitManager); + + 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(new Callable<Boolean>() { + @Override + public Boolean call() throws Exception { + try { + QueryResponse response = client.query(new SolrQuery("*:*")); + + if (response.getResults().getNumFound() > 0) { + assertEquals(100, response.getResults().getNumFound()); + } + } catch (Exception e) { + throw new RuntimeException(e.getMessage()); + } + + return true; + } + }); + } + + futures = executor.invokeAll(callableList); + + for (Future<?> future : futures) { + try { + future.get(); Review comment: Should we assert anything about the result of this? ########## File path: solr/core/src/test/org/apache/solr/servlet/TestRequestRateLimiter.java ########## @@ -0,0 +1,185 @@ +/* + * 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 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; + +public class TestRequestRateLimiter extends SolrCloudTestCase { + private final static String COLLECTION = "c1"; + + @BeforeClass + public static void setupCluster() throws Exception { + configureCluster(1).addConfig(COLLECTION, configset("cloud-minimal")).configure(); + } + + @Test + public void testConcurrentQueries() throws Exception { + CloudSolrClient client = cluster.getSolrClient(); + client.setDefaultCollection(COLLECTION); + + CollectionAdminRequest.createCollection(COLLECTION, 1, 1).process(client); + cluster.waitForActiveCollection(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 */); + RateLimitManager.Builder builder = new MockBuilder(new MockRequestRateLimiter(rateLimiterConfig, 5)); + RateLimitManager rateLimitManager = builder.build(); + + solrDispatchFilter.replaceRateLimitManager(rateLimitManager); + + 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(new Callable<Boolean>() { + @Override + public Boolean call() throws Exception { + try { + QueryResponse response = client.query(new SolrQuery("*:*")); + + if (response.getResults().getNumFound() > 0) { Review comment: should this ever be false? ---------------------------------------------------------------- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. For queries about this service, please contact Infrastructure at: us...@infra.apache.org --------------------------------------------------------------------- To unsubscribe, e-mail: issues-unsubscr...@lucene.apache.org For additional commands, e-mail: issues-h...@lucene.apache.org