cpoerschke commented on code in PR #1725: URL: https://github.com/apache/solr/pull/1725#discussion_r1308559589
########## solr/core/src/test-files/solr/collection1/conf/solrconfig-pluggable-circuitbreaker.xml: ########## @@ -0,0 +1,95 @@ +<?xml version="1.0" ?> + +<!-- + 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. +--> + +<config> + <luceneMatchVersion>${tests.luceneMatchVersion:LATEST}</luceneMatchVersion> + <dataDir>${solr.data.dir:}</dataDir> + <xi:include href="solrconfig.snippet.randomindexconfig.xml" xmlns:xi="http://www.w3.org/2001/XInclude"/> + <directoryFactory name="DirectoryFactory" class="${solr.directoryFactory:solr.RAMDirectoryFactory}"/> + <schemaFactory class="ClassicIndexSchemaFactory"/> + <requestHandler name="/select" class="solr.SearchHandler" /> + + <query> + <!-- Maximum number of clauses in a boolean query... can affect + range or wildcard queries that expand to big boolean + queries. An exception is thrown if exceeded. + --> + <maxBooleanClauses>${solr.max.booleanClauses:1024}</maxBooleanClauses> + + <!-- Cache specification for Filters or DocSets - unordered set of *all* documents + that match a particular query. + --> + <filterCache + enabled="${filterCache.enabled}" + size="512" + initialSize="512" + autowarmCount="2"/> + + <queryResultCache + enabled="${queryResultCache.enabled}" + size="512" + initialSize="512" + autowarmCount="2"/> + + <documentCache + enabled="${documentCache.enabled}" + size="512" + initialSize="512" + autowarmCount="0"/> + + <cache + name="user_defined_cache_XXX" + enabled="${user_defined_cache_XXX.enabled:false}" + /> + <cache + name="user_defined_cache_ZZZ" + enabled="${user_defined_cache_ZZZ.enabled:false}" + /> + + + + <!-- If true, stored fields that are not requested will be loaded lazily. + --> + <enableLazyFieldLoading>true</enableLazyFieldLoading> + + <queryResultWindowSize>10</queryResultWindowSize> + + <!-- boolToFilterOptimizer converts boolean clauses with zero boost + into cached filters if the number of docs selected by the clause exceeds + the threshold (represented as a fraction of the total index) + --> + <boolTofilterOptimizer enabled="false" cacheSize="32" threshold=".05"/> + + </query> + + <circuitBreaker class="solr.MemoryCircuitBreaker"> + <int name="threshold">75</int> Review Comment: ```suggestion <double name="threshold">75</double> ``` ########## solr/core/src/test/org/apache/solr/util/BaseTestCircuitBreaker.java: ########## @@ -0,0 +1,314 @@ +/* + * 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.util; + +import static org.hamcrest.CoreMatchers.containsString; + +import java.lang.invoke.MethodHandles; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Future; +import java.util.concurrent.atomic.AtomicInteger; +import org.apache.solr.SolrTestCaseJ4; +import org.apache.solr.common.SolrException; +import org.apache.solr.common.params.CommonParams; +import org.apache.solr.common.util.ExecutorUtil; +import org.apache.solr.common.util.SolrNamedThreadFactory; +import org.apache.solr.util.circuitbreaker.CPUCircuitBreaker; +import org.apache.solr.util.circuitbreaker.CircuitBreaker; +import org.apache.solr.util.circuitbreaker.MemoryCircuitBreaker; +import org.hamcrest.MatcherAssert; +import org.junit.After; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public abstract class BaseTestCircuitBreaker extends SolrTestCaseJ4 { + private static final Logger log = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass()); + + protected static void indexDocs() { + for (int i = 0; i < 20; i++) { + assertU(adoc("name", "john smith", "id", "1")); + assertU(adoc("name", "johathon smith", "id", "2")); + assertU(adoc("name", "john percival smith", "id", "3")); + assertU(adoc("id", "1", "title", "this is a title.", "inStock_b1", "true")); + assertU(adoc("id", "2", "title", "this is another title.", "inStock_b1", "true")); + assertU(adoc("id", "3", "title", "Mary had a little lamb.", "inStock_b1", "false")); + + // commit inside the loop to get multiple segments to make search as realistic as possible + assertU(commit()); + } + } + + @Override + public void tearDown() throws Exception { + super.tearDown(); + } + + @After + public void after() { + h.getCore().getCircuitBreakerRegistry().deregisterAll(); + } + + public void testCBAlwaysTrips() { + removeAllExistingCircuitBreakers(); + + CircuitBreaker circuitBreaker = new MockCircuitBreaker(true); + + h.getCore().getCircuitBreakerRegistry().register(circuitBreaker); + + expectThrows( + SolrException.class, + () -> { + h.query(req("name:\"john smith\"")); + }); + } + + public void testCBFakeMemoryPressure() { + removeAllExistingCircuitBreakers(); + + CircuitBreaker circuitBreaker = new FakeMemoryPressureCircuitBreaker(); + MemoryCircuitBreaker memoryCircuitBreaker = (MemoryCircuitBreaker) circuitBreaker; + + memoryCircuitBreaker.setThreshold(75); + + h.getCore().getCircuitBreakerRegistry().register(circuitBreaker); + + expectThrows( + SolrException.class, + () -> { + h.query(req("name:\"john smith\"")); + }); + } + + public void testBuildingMemoryPressure() { + ExecutorService executor = + ExecutorUtil.newMDCAwareCachedThreadPool(new SolrNamedThreadFactory("TestCircuitBreaker")); + + AtomicInteger failureCount = new AtomicInteger(); + + try { + removeAllExistingCircuitBreakers(); + + CircuitBreaker circuitBreaker = new BuildingUpMemoryPressureCircuitBreaker(); + MemoryCircuitBreaker memoryCircuitBreaker = (MemoryCircuitBreaker) circuitBreaker; + + memoryCircuitBreaker.setThreshold(75); + + h.getCore().getCircuitBreakerRegistry().register(circuitBreaker); + + List<Future<?>> futures = new ArrayList<>(); + + for (int i = 0; i < 5; i++) { + Future<?> future = + executor.submit( + () -> { + try { + h.query(req("name:\"john smith\"")); + } catch (SolrException e) { + MatcherAssert.assertThat( + e.getMessage(), containsString("Circuit Breakers tripped")); + failureCount.incrementAndGet(); + } catch (Exception e) { + throw new RuntimeException(e.getMessage()); + } + }); + + futures.add(future); + } + + for (Future<?> future : futures) { + try { + future.get(); + } catch (Exception e) { + throw new RuntimeException(e.getMessage()); + } + } + } finally { + ExecutorUtil.shutdownAndAwaitTermination(executor); + assertEquals("Number of failed queries is not correct", 1, failureCount.get()); + } + } + + public void testFakeCPUCircuitBreaker() { + removeAllExistingCircuitBreakers(); + + CircuitBreaker circuitBreaker = new FakeCPUCircuitBreaker(); + CPUCircuitBreaker cpuCircuitBreaker = (CPUCircuitBreaker) circuitBreaker; + + cpuCircuitBreaker.setThreshold(75); + + h.getCore().getCircuitBreakerRegistry().register(circuitBreaker); + + AtomicInteger failureCount = new AtomicInteger(); + + ExecutorService executor = + ExecutorUtil.newMDCAwareCachedThreadPool(new SolrNamedThreadFactory("TestCircuitBreaker")); + try { + List<Future<?>> futures = new ArrayList<>(); + + for (int i = 0; i < 5; i++) { + Future<?> future = + executor.submit( + () -> { + try { + h.query(req("name:\"john smith\"")); + } catch (SolrException e) { + MatcherAssert.assertThat( + e.getMessage(), containsString("Circuit Breakers tripped")); + failureCount.incrementAndGet(); + } catch (Exception e) { + throw new RuntimeException(e.getMessage()); + } + }); + + futures.add(future); + } + + for (Future<?> future : futures) { + try { + future.get(); + } catch (Exception e) { + throw new RuntimeException(e.getMessage()); + } + } + } finally { + ExecutorUtil.shutdownAndAwaitTermination(executor); + assertEquals("Number of failed queries is not correct", 5, failureCount.get()); + } + } + + public void testResponseWithCBTiming() { + removeAllExistingCircuitBreakers(); + + assertQ( + req("q", "*:*", CommonParams.DEBUG_QUERY, "true"), + "//str[@name='rawquerystring']='*:*'", + "//str[@name='querystring']='*:*'", + "//str[@name='parsedquery']='MatchAllDocsQuery(*:*)'", + "//str[@name='parsedquery_toString']='*:*'", + "count(//lst[@name='explain']/*)=3", + "//lst[@name='explain']/str[@name='1']", + "//lst[@name='explain']/str[@name='2']", + "//lst[@name='explain']/str[@name='3']", + "//str[@name='QParser']", + "count(//lst[@name='timing']/*)=3", + "//lst[@name='timing']/double[@name='time']", + "count(//lst[@name='prepare']/*)>0", + "//lst[@name='prepare']/double[@name='time']", + "count(//lst[@name='process']/*)>0", + "//lst[@name='process']/double[@name='time']"); + + CircuitBreaker circuitBreaker = new MockCircuitBreaker(false); + h.getCore().getCircuitBreakerRegistry().register(circuitBreaker); + + assertQ( + req("q", "*:*", CommonParams.DEBUG_QUERY, "true"), + "//str[@name='rawquerystring']='*:*'", + "//str[@name='querystring']='*:*'", + "//str[@name='parsedquery']='MatchAllDocsQuery(*:*)'", + "//str[@name='parsedquery_toString']='*:*'", + "count(//lst[@name='explain']/*)=3", + "//lst[@name='explain']/str[@name='1']", + "//lst[@name='explain']/str[@name='2']", + "//lst[@name='explain']/str[@name='3']", + "//str[@name='QParser']", + "count(//lst[@name='timing']/*)=4", + "//lst[@name='timing']/double[@name='time']", + "count(//lst[@name='circuitbreaker']/*)>0", + "//lst[@name='circuitbreaker']/double[@name='time']", + "count(//lst[@name='prepare']/*)>0", + "//lst[@name='prepare']/double[@name='time']", + "count(//lst[@name='process']/*)>0", + "//lst[@name='process']/double[@name='time']"); + } + + private void removeAllExistingCircuitBreakers() { + List<CircuitBreaker> registeredCircuitBreakers = + h.getCore().getCircuitBreakerRegistry().getRegisteredCircuitBreakers(); + + registeredCircuitBreakers.clear(); Review Comment: Could `deregisterAll` be used here instead (and then `getRegisteredCircuitBreakers()` could be removed)? ```suggestion h.getCore().getCircuitBreakerRegistry().deregisterAll(); ``` ########## solr/core/src/java/org/apache/solr/util/circuitbreaker/CircuitBreakerManager.java: ########## @@ -17,163 +17,99 @@ package org.apache.solr.util.circuitbreaker; -import com.google.common.annotations.VisibleForTesting; -import java.util.ArrayList; -import java.util.List; +import java.lang.invoke.MethodHandles; import org.apache.solr.common.util.NamedList; -import org.apache.solr.core.PluginInfo; -import org.apache.solr.util.plugin.PluginInfoInitialized; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** - * Manages all registered circuit breaker instances. Responsible for a holistic view of whether a - * circuit breaker has tripped or not. + * Single CircuitBreaker that registers both a Memory and a CPU CircuitBreaker. This is only for + * backward compatibility with the 9.x versions prior to 9.4. * - * <p>There are two typical ways of using this class's instance: 1. Check if any circuit breaker has - * triggered -- and know which circuit breaker has triggered. 2. Get an instance of a specific - * circuit breaker and perform checks. - * - * <p>It is a good practice to register new circuit breakers here if you want them checked for every - * request. - * - * <p>NOTE: The current way of registering new default circuit breakers is minimal and not a long - * term solution. There will be a follow up with a SIP for a schema API design. + * @deprecated Use individual Circuit Breakers instead */ -public class CircuitBreakerManager implements PluginInfoInitialized { - // Class private to potentially allow "family" of circuit breakers to be enabled or disabled - private final boolean enableCircuitBreakerManager; - - private final List<CircuitBreaker> circuitBreakerList = new ArrayList<>(); - - public CircuitBreakerManager(final boolean enableCircuitBreakerManager) { - this.enableCircuitBreakerManager = enableCircuitBreakerManager; +@Deprecated(since = "9.4") +public class CircuitBreakerManager extends CircuitBreaker { + private static final Logger log = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass()); + private boolean cpuEnabled; + private boolean memEnabled; + private int memThreshold = 100; + private int cpuThreshold = 100; + private MemoryCircuitBreaker memCB; + private CPUCircuitBreaker cpuCB; + + public CircuitBreakerManager() { + super(); } @Override - public void init(PluginInfo pluginInfo) { - CircuitBreaker.CircuitBreakerConfig circuitBreakerConfig = buildCBConfig(pluginInfo); - - // Install the default circuit breakers - CircuitBreaker memoryCircuitBreaker = new MemoryCircuitBreaker(circuitBreakerConfig); - CircuitBreaker cpuCircuitBreaker = new CPUCircuitBreaker(circuitBreakerConfig); - - register(memoryCircuitBreaker); - register(cpuCircuitBreaker); - } - - public void register(CircuitBreaker circuitBreaker) { - circuitBreakerList.add(circuitBreaker); + public boolean isTripped() { + return (memEnabled && memCB.isTripped()) || (cpuEnabled && cpuCB.isTripped()); } - public void deregisterAll() { - circuitBreakerList.clear(); - } - /** - * Check and return circuit breakers that have triggered - * - * @return CircuitBreakers which have triggered, null otherwise. - */ - public List<CircuitBreaker> checkTripped() { - List<CircuitBreaker> triggeredCircuitBreakers = null; - - if (enableCircuitBreakerManager) { - for (CircuitBreaker circuitBreaker : circuitBreakerList) { - if (circuitBreaker.isEnabled() && circuitBreaker.isTripped()) { - if (triggeredCircuitBreakers == null) { - triggeredCircuitBreakers = new ArrayList<>(); - } - - triggeredCircuitBreakers.add(circuitBreaker); - } - } + @Override + public String getDebugInfo() { + StringBuilder sb = new StringBuilder(); + if (memEnabled) { + sb.append(memCB.getDebugInfo()).append("\n"); } Review Comment: ```suggestion if (memEnabled) { sb.append(memCB.getDebugInfo()); } if (memEnabled && cpuEnabled) { sb.append("\n"); } ``` -- 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. To unsubscribe, e-mail: issues-unsubscr...@solr.apache.org For queries about this service, please contact Infrastructure at: us...@infra.apache.org --------------------------------------------------------------------- To unsubscribe, e-mail: issues-unsubscr...@solr.apache.org For additional commands, e-mail: issues-h...@solr.apache.org