Skip to content

Commit 7391b7d

Browse files
SOLR-18564: CoreContainer.shutdown: run the remaining closes when the client close pool times out (#5192)
1 parent f489a30 commit 7391b7d

5 files changed

Lines changed: 212 additions & 9 deletions

File tree

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
title: "CoreContainer.shutdown: a client close pool timeout skips the remaining closes and leaks metrics contexts"
2+
type: fixed
3+
authors:
4+
- name: Nick Shanin
5+
links:
6+
- name: SOLR-18564
7+
url: https://issues.apache.org/jira/browse/SOLR-18564

‎solr/core/src/java/org/apache/solr/core/CoreContainer.java‎

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -93,6 +93,7 @@
9393
import org.apache.solr.common.util.CollectionUtil;
9494
import org.apache.solr.common.util.EnvUtils;
9595
import org.apache.solr.common.util.ExecutorUtil;
96+
import org.apache.solr.common.util.ExecutorUtil.ExecutorTerminationTimeoutException;
9697
import org.apache.solr.common.util.IOUtils;
9798
import org.apache.solr.common.util.ObjectCache;
9899
import org.apache.solr.common.util.SolrNamedThreadFactory;
@@ -1312,7 +1313,17 @@ public void shutdown() {
13121313
// we want to close zk stuff last
13131314
zkSys.close();
13141315
} finally {
1315-
ExecutorUtil.shutdownAndAwaitTermination(customThreadPool);
1316+
try {
1317+
ExecutorUtil.shutdownAndAwaitTermination(customThreadPool);
1318+
} catch (ExecutorTerminationTimeoutException e) {
1319+
// A close task that outlives the pool's termination budget must not abort the
1320+
// rest of shutdown. The closes after this block (the plugin closes, the
1321+
// container handlers and the root metrics context) are the only release path
1322+
// for the container's metrics contexts, so skipping them leaks the whole
1323+
// metrics tree of this container.
1324+
log.warn(
1325+
"The closeThreadPool did not terminate; continuing CoreContainer shutdown.", e);
1326+
}
13161327
}
13171328
}
13181329
}
Lines changed: 163 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,163 @@
1+
/*
2+
* Licensed to the Apache Software Foundation (ASF) under one or more
3+
* contributor license agreements. See the NOTICE file distributed with
4+
* this work for additional information regarding copyright ownership.
5+
* The ASF licenses this file to You under the Apache License, Version 2.0
6+
* (the "License"); you may not use this file except in compliance with
7+
* the License. You may obtain a copy of the License at
8+
*
9+
* http://www.apache.org/licenses/LICENSE-2.0
10+
*
11+
* Unless required by applicable law or agreed to in writing, software
12+
* distributed under the License is distributed on an "AS IS" BASIS,
13+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14+
* See the License for the specific language governing permissions and
15+
* limitations under the License.
16+
*/
17+
package org.apache.solr.core;
18+
19+
import java.io.IOException;
20+
import java.nio.file.Path;
21+
import java.util.concurrent.CountDownLatch;
22+
import java.util.concurrent.TimeUnit;
23+
import java.util.concurrent.atomic.AtomicBoolean;
24+
import org.apache.solr.SolrTestCase;
25+
import org.apache.solr.SolrTestCaseJ4;
26+
import org.apache.solr.common.util.ObjectReleaseTracker;
27+
import org.apache.solr.handler.RequestHandlerBase;
28+
import org.apache.solr.handler.component.HttpShardHandlerFactory;
29+
import org.apache.solr.handler.component.ShardHandlerFactory;
30+
import org.apache.solr.metrics.SolrMetricsContext;
31+
import org.apache.solr.request.SolrQueryRequest;
32+
import org.apache.solr.response.SolrQueryResponse;
33+
import org.apache.solr.security.AuthorizationContext;
34+
import org.apache.solr.security.PermissionNameProvider;
35+
import org.junit.BeforeClass;
36+
import org.junit.Test;
37+
38+
/**
39+
* Shutdown must run its trailing closes even when a close task outlives the closeThreadPool's
40+
* termination budget and the pool wait throws. Those closes are the only release path for the
41+
* container's metrics contexts; skipping them leaks the whole metrics tree, and in a test JVM the
42+
* leaked contexts are then charged to an unrelated suite by the object release tracker.
43+
*/
44+
public class CoreContainerShutdownTest extends SolrTestCase {
45+
46+
private static final String SOLR_XML =
47+
"<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n"
48+
+ "<solr>\n"
49+
+ "<str name=\"configSetBaseDir\">${configsets:configsets}</str>\n"
50+
+ "</solr>";
51+
52+
@BeforeClass
53+
public static void beforeClass() {
54+
System.setProperty(
55+
"configsets", SolrTestCaseJ4.getFile("solr/configsets").toAbsolutePath().toString());
56+
}
57+
58+
@Test
59+
public void testShutdownRunsTrailingClosesWhenClosePoolTimesOut() throws Exception {
60+
Path solrHome = createTempDir();
61+
CoreContainer cc = new CoreContainer(SolrXmlConfig.fromString(solrHome, SOLR_XML));
62+
cc.load();
63+
BlockingShardHandlerFactory blockingFactory = null;
64+
try {
65+
assertTrue(
66+
"the root metrics context is tracked after load",
67+
ObjectReleaseTracker.getTrackedObjectsOfType(SolrMetricsContext.class)
68+
.contains(cc.solrMetricsContext));
69+
70+
CloseTrackingHandler handler = new CloseTrackingHandler();
71+
cc.getRequestHandlers().put("/close-tracking", handler);
72+
73+
// Make one close task outlive the pool's whole termination budget (both 60 second
74+
// awaits), so the pool wait throws the way it did in the incident this test pins down.
75+
// This makes the test take about two minutes; the wait is the production timeout,
76+
// not a test sleep.
77+
blockingFactory = new BlockingShardHandlerFactory(cc.shardHandlerFactory);
78+
cc.shardHandlerFactory = blockingFactory;
79+
80+
cc.shutdown();
81+
82+
assertTrue(
83+
"container handlers must be closed even when the close pool times out",
84+
handler.closed.get());
85+
assertFalse(
86+
"the root metrics context must be released even when the close pool times out",
87+
ObjectReleaseTracker.getTrackedObjectsOfType(SolrMetricsContext.class)
88+
.contains(cc.solrMetricsContext));
89+
} finally {
90+
if (blockingFactory != null) {
91+
blockingFactory.releaseClose();
92+
// Wait for the blocked close task to finish so the delegate factory is closed
93+
// before the framework's post-class object release check runs.
94+
assertTrue(blockingFactory.awaitCloseFinished(30, TimeUnit.SECONDS));
95+
}
96+
}
97+
}
98+
99+
/** A container handler whose close is observable. */
100+
private static final class CloseTrackingHandler extends RequestHandlerBase {
101+
final AtomicBoolean closed = new AtomicBoolean();
102+
103+
@Override
104+
public void handleRequestBody(SolrQueryRequest req, SolrQueryResponse rsp) {}
105+
106+
@Override
107+
public String getDescription() {
108+
return "test handler that records its close";
109+
}
110+
111+
@Override
112+
public PermissionNameProvider.Name getPermissionName(AuthorizationContext request) {
113+
return PermissionNameProvider.Name.ALL;
114+
}
115+
116+
@Override
117+
public void close() throws IOException {
118+
closed.set(true);
119+
super.close();
120+
}
121+
}
122+
123+
/**
124+
* Wraps the real shard handler factory with a close that blocks until released, surviving the
125+
* pool's force-stop interrupt the way a stuck Jetty client close does, and only then delegates.
126+
*/
127+
private static final class BlockingShardHandlerFactory extends HttpShardHandlerFactory {
128+
private final ShardHandlerFactory delegate;
129+
private final CountDownLatch release = new CountDownLatch(1);
130+
private final CountDownLatch closeFinished = new CountDownLatch(1);
131+
132+
BlockingShardHandlerFactory(ShardHandlerFactory delegate) {
133+
this.delegate = delegate;
134+
}
135+
136+
@Override
137+
public void close() {
138+
try {
139+
boolean released = false;
140+
while (!released) {
141+
try {
142+
release.await();
143+
released = true;
144+
} catch (InterruptedException e) {
145+
// Keep blocking: the pool's force-stop interrupts its workers, and a close stuck
146+
// inside the client shutdown survives that interrupt without finishing.
147+
}
148+
}
149+
delegate.close();
150+
} finally {
151+
closeFinished.countDown();
152+
}
153+
}
154+
155+
void releaseClose() {
156+
release.countDown();
157+
}
158+
159+
boolean awaitCloseFinished(long timeout, TimeUnit unit) throws InterruptedException {
160+
return closeFinished.await(timeout, unit);
161+
}
162+
}
163+
}

‎solr/solrj/src/java/org/apache/solr/common/util/ExecutorUtil.java‎

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -112,13 +112,19 @@ public static boolean isTerminated(ExecutorService pool) {
112112
* detail on the waiting can be found in {@link #awaitTermination(ExecutorService)}.
113113
*
114114
* @param pool The ExecutorService to shut down and wait on
115+
* @throws ExecutorTerminationTimeoutException if the pool does not terminate after both waits
115116
*/
116117
public static void shutdownAndAwaitTermination(ExecutorService pool) {
117118
if (pool == null) return;
118119
pool.shutdown(); // Disable new tasks from being submitted
119120
awaitTermination(pool);
120121
}
121122

123+
/**
124+
* Interrupt the pool's tasks and wait for termination.
125+
*
126+
* @throws ExecutorTerminationTimeoutException if the pool does not terminate after both waits
127+
*/
122128
public static void shutdownNowAndAwaitTermination(ExecutorService pool) {
123129
if (pool == null) return;
124130
pool.shutdownNow(); // Disable new tasks from being submitted; interrupt existing tasks
@@ -130,6 +136,7 @@ public static void shutdownNowAndAwaitTermination(ExecutorService pool) {
130136
* shutdown the remaining threads and wait another 60 seconds.
131137
*
132138
* @param pool the ExecutorService to wait on
139+
* @throws ExecutorTerminationTimeoutException if the pool does not terminate after both waits
133140
*/
134141
public static void awaitTermination(ExecutorService pool) {
135142
awaitTermination(pool, 60, TimeUnit.SECONDS);
@@ -146,7 +153,8 @@ static void awaitTermination(ExecutorService pool, long timeout, TimeUnit unit)
146153
if (!pool.awaitTermination(timeout, unit)) {
147154
String executorDetails = describeExecutorForLogging(pool);
148155
log.error("Threads from pool did not forcefully stop. {}", executorDetails);
149-
throw new RuntimeException("Timeout waiting for pool to shutdown. " + executorDetails);
156+
throw new ExecutorTerminationTimeoutException(
157+
"Timeout waiting for pool to shutdown. " + executorDetails);
150158
}
151159
}
152160
} catch (InterruptedException ie) {
@@ -157,6 +165,13 @@ static void awaitTermination(ExecutorService pool, long timeout, TimeUnit unit)
157165
}
158166
}
159167

168+
/** The executor did not terminate within either the graceful or forced shutdown wait. */
169+
public static final class ExecutorTerminationTimeoutException extends RuntimeException {
170+
private ExecutorTerminationTimeoutException(String message) {
171+
super(message);
172+
}
173+
}
174+
160175
/** Executor logging details which include pool name when executor fails to terminate. */
161176
public static String describeExecutorForLogging(ExecutorService pool) {
162177
if (pool == null) return "";

‎solr/solrj/src/test/org/apache/solr/common/util/ExecutorUtilTest.java‎

Lines changed: 14 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@
3030
import java.util.concurrent.atomic.AtomicLong;
3131
import org.apache.lucene.util.NamedThreadFactory;
3232
import org.apache.solr.SolrTestCase;
33+
import org.apache.solr.common.util.ExecutorUtil.ExecutorTerminationTimeoutException;
3334
import org.apache.solr.logging.MDCLoggingContext;
3435
import org.apache.solr.util.TimeOut;
3536
import org.junit.Test;
@@ -52,9 +53,9 @@ public class ExecutorUtilTest extends SolrTestCase {
5253
public void testExecutorUtilAwaitsTerminationWhenTaskIgnoresInterupt() throws Exception {
5354

5455
final Worker w = new Worker(false);
56+
final String poolName = this.getClass().getSimpleName() + "non-interruptable";
5557
final ExecutorService executorService =
56-
ExecutorUtil.newMDCAwareSingleThreadExecutor(
57-
new SolrNamedThreadFactory(this.getClass().getSimpleName() + "non-interruptable"));
58+
ExecutorUtil.newMDCAwareSingleThreadExecutor(new SolrNamedThreadFactory(poolName));
5859
try {
5960
final Future<Boolean> f = executorService.submit(w);
6061

@@ -63,11 +64,17 @@ public void testExecutorUtilAwaitsTerminationWhenTaskIgnoresInterupt() throws Ex
6364
assertTrue(
6465
"Worker not interupted by shutdown in a sane amount of time",
6566
w.awaitWorkerInteruptedAtLeastOnce());
66-
assertThrows(
67-
RuntimeException.class,
68-
() ->
69-
ExecutorUtil.awaitTermination(
70-
executorService, MAX_AWAIT_TERMINATION_ARG_MS, TimeUnit.MILLISECONDS));
67+
RuntimeException timeout =
68+
assertThrows(
69+
ExecutorTerminationTimeoutException.class,
70+
() ->
71+
ExecutorUtil.awaitTermination(
72+
executorService, MAX_AWAIT_TERMINATION_ARG_MS, TimeUnit.MILLISECONDS));
73+
assertTrue(
74+
timeout.getMessage(),
75+
timeout.getMessage().startsWith("Timeout waiting for pool to shutdown. "));
76+
assertTrue(
77+
timeout.getMessage(), timeout.getMessage().contains("[poolName=" + poolName + "]"));
7178

7279
assertFalse("Worker should not finish due to shutdown or awaitTermination", f.isDone());
7380
assertTrue("test sanity check: WTF? how did we get here?", w.getNumberOfInterupts() > 0);

0 commit comments

Comments
 (0)