This is an automated email from the ASF dual-hosted git repository.
markt-asf pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/tomcat.git
The following commit(s) were added to refs/heads/main by this push:
new b89e338575 Fix HTTP/2 sendfile clean-up issues found in review
b89e338575 is described below
commit b89e3385759dc762d204332a4ead836ad0a247d2
Author: Mark Thomas <[email protected]>
AuthorDate: Tue Dec 1 12:36:54 2026 +0000
Fix HTTP/2 sendfile clean-up issues found in review
- Do not return the request and response to the pool if the connection is
closed while a sendfile write is in progress. A callback for the write may
still be using them and another stream, possibly on another connection,
could obtain them.
- Keep an earlier decision not to re-use the request and response (e.g.
after
a timeout) when the clean-up is deferred until a sendfile write finishes.
- Do not count a request twice when the sendfile operation is started during
an asynchronous dispatch. Only service() returning SENDFILE leaves the
statistics to be updated when the operation finishes.
- Update the statistics for a request that is cleaned up because the
connection was closed before the sendfile operation finished.
- Add Stream.isRecycleComplete() so that tests can wait until recycling,
including returning the request and response to the pool, has finished.
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
---
java/org/apache/coyote/http2/Stream.java | 27 +++++++++---
java/org/apache/coyote/http2/StreamProcessor.java | 48 ++++++++++++++++++++--
.../org/apache/coyote/http2/TestHttp2Sendfile.java | 47 +++++++++++++++++----
3 files changed, 106 insertions(+), 16 deletions(-)
diff --git a/java/org/apache/coyote/http2/Stream.java
b/java/org/apache/coyote/http2/Stream.java
index d2cf146c8e..4421ceb6a1 100644
--- a/java/org/apache/coyote/http2/Stream.java
+++ b/java/org/apache/coyote/http2/Stream.java
@@ -112,6 +112,7 @@ class Stream extends AbstractNonZeroStream implements
HeaderEmitter {
private final Object recycledLock = new Object();
private volatile boolean recycled = false;
+ private volatile boolean recycleComplete = false;
// The processor handling the request for this stream. Set when the
processor is created.
private volatile StreamProcessor streamProcessor = null;
// A stream error raised by the connection thread while the processor was
still processing the request.
@@ -959,6 +960,16 @@ class Stream extends AbstractNonZeroStream implements
HeaderEmitter {
}
+ /*
+ * Package private only so that tests can wait until recycling has
finished, including returning the request and
+ * response to the pool if that was allowed, before checking the result.
isRecycled() is true as soon as recycling
+ * starts. Not used by production code.
+ */
+ final boolean isRecycleComplete() {
+ return recycleComplete;
+ }
+
+
/*
* Package private only so that tests can obtain the processor for a
stream without using reflection. Not used by
* production code.
@@ -1065,12 +1076,16 @@ class Stream extends AbstractNonZeroStream implements
HeaderEmitter {
if (log.isTraceEnabled()) {
log.trace(sm.getString("stream.recycle.first", getConnectionId(),
getIdAsString()));
}
- // Notes are not reset when request is recycled but this is a per
request note
- coyoteRequest.setNote(Request.NOTE_BAD_REQUEST, null);
- coyoteRequest.recycle();
- coyoteResponse.recycle();
- if (reuseRequestAndResponse) {
- handler.getProtocol().pushRequestAndResponse(coyoteRequest);
+ try {
+ // Notes are not reset when request is recycled but this is a per
request note
+ coyoteRequest.setNote(Request.NOTE_BAD_REQUEST, null);
+ coyoteRequest.recycle();
+ coyoteResponse.recycle();
+ if (reuseRequestAndResponse) {
+ handler.getProtocol().pushRequestAndResponse(coyoteRequest);
+ }
+ } finally {
+ recycleComplete = true;
}
}
diff --git a/java/org/apache/coyote/http2/StreamProcessor.java
b/java/org/apache/coyote/http2/StreamProcessor.java
index a71cd4fbc6..013f90cadd 100644
--- a/java/org/apache/coyote/http2/StreamProcessor.java
+++ b/java/org/apache/coyote/http2/StreamProcessor.java
@@ -75,6 +75,18 @@ class StreamProcessor extends AbstractProcessor implements
NonPipeliningProcesso
* it is read, without holding processLock, when the connection is closed.
*/
private volatile boolean sendfileCleanupDeferred = false;
+ /*
+ * Set if an event has decided that the request and response must not be
returned to the pool for re-use but the
+ * clean-up, which includes recycling, has been deferred until a sendfile
write finishes. Only accessed while
+ * holding processLock.
+ */
+ private boolean sendfileReuseDisallowed = false;
+ /*
+ * True if service() returned SocketState.SENDFILE, which means that
nothing has updated the request statistics. In
+ * all other cases the statistics are updated before the clean-up is
started (by service() or by the code that
+ * processes an asynchronous dispatch). Only accessed while holding
processLock.
+ */
+ private boolean sendfileStatisticsPending = false;
private SendfileData sendfileData = null;
private SendfileState sendfileState = null;
@@ -167,11 +179,23 @@ class StreamProcessor extends AbstractProcessor
implements NonPipeliningProcesso
*/
sendfileCleanupDeferred = true;
cleanupDeferred = !handler.isConnectionClosed();
+ if (!cleanupDeferred) {
+ /*
+ * The connection has been closed so the clean-up
can't wait for the write. A callback for
+ * the write may already be running, and still
using the request and response, so don't
+ * allow another stream, possibly on another
connection, to obtain them.
+ */
+ reuseRequestAndResponse = false;
+ }
}
if (sendfileData != null && sendfileData.failed) {
// A failed write may not have released everything it
used
reuseRequestAndResponse = false;
}
+ if (cleanupDeferred && !reuseRequestAndResponse) {
+ // Remember the decision (e.g. after a timeout) for
when the clean-up is performed
+ sendfileReuseDisallowed = true;
+ }
if (state == SocketState.LONG) {
waiting = true;
@@ -197,6 +221,12 @@ class StreamProcessor extends AbstractProcessor implements
NonPipeliningProcesso
reuseRequestAndResponse = false;
} finally {
if (state == SocketState.CLOSED && !cleanupDeferred) {
+ if (sendfileStatisticsPending) {
+ // service() returned SENDFILE and the sendfile
operation has not been cleaned up (e.g.
+ // the connection was closed) so nothing has
updated the statistics
+ sendfileStatisticsPending = false;
+ request.updateCounters();
+ }
/*
* Recycle this processor before the stream is
recycled as recycling the stream will add the
* request and the response to the pool for re-use (if
re-use is enabled) and the request
@@ -603,14 +633,24 @@ class StreamProcessor extends AbstractProcessor
implements NonPipeliningProcesso
return;
}
handler.getProtocol().getHttp11Protocol().removeWaitingProcessor(this);
- request.updateCounters();
+ if (sendfileStatisticsPending) {
+ sendfileStatisticsPending = false;
+ request.updateCounters();
+ }
if (stream.equals(handler.getStream(stream.getIdAsInt()))) {
// Not closed yet. If it has already been closed (and
replaced) only the recycling is left to do.
closeStream();
}
recycle();
- // A failed write may not have released everything it used so
don't re-use the request and response
- stream.recycle(getErrorState().isIoAllowed() && !(sendfileData !=
null && sendfileData.failed));
+ /*
+ * A failed write may not have released everything it used so
don't re-use the request and response. Also
+ * respect any earlier decision not to re-use them. If the
connection has been closed, don't re-use them
+ * whichever thread performs the clean-up. Whether the write
finishes first, or the connection being closed
+ * triggers the clean-up first, depends on the connector and on
timing. Not re-using them makes the outcome
+ * the same in both cases.
+ */
+ stream.recycle(getErrorState().isIoAllowed() &&
!sendfileReuseDisallowed &&
+ !(sendfileData != null && sendfileData.failed) &&
!handler.isConnectionClosed());
} finally {
processLock.unlock();
}
@@ -683,6 +723,8 @@ class StreamProcessor extends AbstractProcessor implements
NonPipeliningProcesso
request.updateCounters();
return SocketState.CLOSED;
}
+ // The statistics are updated when the sendfile operation finishes
+ sendfileStatisticsPending = true;
return SocketState.SENDFILE;
} else if (isAsync() && getErrorState().isIoAllowed()) {
/*
diff --git a/test/org/apache/coyote/http2/TestHttp2Sendfile.java
b/test/org/apache/coyote/http2/TestHttp2Sendfile.java
index cd98243d26..95cf0a9b62 100644
--- a/test/org/apache/coyote/http2/TestHttp2Sendfile.java
+++ b/test/org/apache/coyote/http2/TestHttp2Sendfile.java
@@ -331,7 +331,7 @@ public class TestHttp2Sendfile extends Http2TestBase {
*/
@Test
public void testSendfileCompletedByOtherThreadCleanedUp() throws Exception
{
- doCompletedByOtherThreadTest("/sendfile");
+ doCompletedByOtherThreadTest("/sendfile", true);
}
@@ -340,11 +340,22 @@ public class TestHttp2Sendfile extends Http2TestBase {
*/
@Test
public void testAsyncSendfileCompletedByOtherThreadCleanedUp() throws
Exception {
- doCompletedByOtherThreadTest("/asyncsendfile");
+ doCompletedByOtherThreadTest("/asyncsendfile", true);
}
- private void doCompletedByOtherThreadTest(String path) throws Exception {
+ /*
+ * As above but the response is completed, and sendfile used, while
processing an asynchronous timeout. The request
+ * and response must not be returned to the pool for re-use after a
timeout, since application code may still hold
+ * them. That must still be the case when the clean-up is deferred until
the sendfile write has finished.
+ */
+ @Test
+ public void testAsyncTimeoutSendfileCompletedByOtherThreadNotPooled()
throws Exception {
+ doCompletedByOtherThreadTest("/asynctimeoutsendfile", false);
+ }
+
+
+ private void doCompletedByOtherThreadTest(String path, boolean
expectPooled) throws Exception {
sendfilePath = path;
// Allow the entire file to be sent without any further window updates
from the client
startAndSendSendfileRequest(Integer.MAX_VALUE - 65535, 30000);
@@ -365,6 +376,18 @@ public class TestHttp2Sendfile extends Http2TestBase {
}
Assert.assertTrue("Response not completed", ended);
Assert.assertEquals("Stream that was not recycled", 0,
countNotRecycled(Collections.singletonList(stream)));
+
+ // The pool is last in, first out so the request and response, if they
were returned, are next out
+ if (expectPooled) {
+ Assert.assertSame("The request was not returned to the pool",
stream.getCoyoteRequest(),
+ http2Protocol.popRequestAndResponse());
+ } else {
+ Assert.assertNotSame("The request was returned to the pool",
stream.getCoyoteRequest(),
+ http2Protocol.popRequestAndResponse());
+ }
+
+ // Stream 1 (the upgrade request) and stream 3. Each must be counted
exactly once.
+ Assert.assertEquals("Each request must be counted once", 2,
http2Protocol.getGlobal().getRequestCount());
}
@@ -395,7 +418,7 @@ public class TestHttp2Sendfile extends Http2TestBase {
Assert.assertFalse("The stream was recycled while a sendfile write was
pending", stream.isRecycled());
// Read again so that the pending write finishes
- readUntil("The write did not finish", stream::isRecycled);
+ readUntil("The write did not finish", stream::isRecycleComplete);
Assert.assertNull("The stream was recycled but not closed",
handler.getStream(3));
// Control for testSendfileWriteTimeoutClosesConnection(). A write
that was cancelled, not failed, is returned to
// the pool. The pool is last in, first out.
@@ -476,6 +499,7 @@ public class TestHttp2Sendfile extends Http2TestBase {
s.close();
Assert.assertEquals("Stream that was not recycled", 0,
countNotRecycled(Collections.singletonList(stream)));
+ Assert.assertEquals("Each request must be counted once", 2,
http2Protocol.getGlobal().getRequestCount());
}
@@ -500,6 +524,13 @@ public class TestHttp2Sendfile extends Http2TestBase {
handler.close();
Assert.assertEquals("Stream that was not recycled", 0,
countNotRecycled(Collections.singletonList(stream)));
+ // A callback for the write may still be running so the request and
response must not be available for re-use
+ // by another stream, possibly on another connection.
+ Assert.assertNotSame("The request was returned to the pool",
stream.getCoyoteRequest(),
+ http2Protocol.popRequestAndResponse());
+ // Stream 1 (the upgrade request) and stream 3. The request must be
counted even though the clean-up was
+ // triggered by the connection being closed and not by the write
finishing.
+ Assert.assertEquals("Each request must be counted once", 2,
http2Protocol.getGlobal().getRequestCount());
}
@@ -531,6 +562,8 @@ public class TestHttp2Sendfile extends Http2TestBase {
handler.close();
Assert.assertEquals("Stream that was not recycled", 0,
countNotRecycled(Collections.singletonList(stream)));
+ Assert.assertNotSame("The request was returned to the pool",
stream.getCoyoteRequest(),
+ http2Protocol.popRequestAndResponse());
}
@@ -652,7 +685,7 @@ public class TestHttp2Sendfile extends Http2TestBase {
sendRst(3, Http2Error.CANCEL.getCode());
// Wait for the server to process the reset
- readUntil("The reset was not processed", stream::isRecycled);
+ readUntil("The reset was not processed", stream::isRecycleComplete);
// Give the connection just enough window for the response to a new
request.
sendSimpleGetRequest(5);
@@ -699,7 +732,7 @@ public class TestHttp2Sendfile extends Http2TestBase {
// Drain anything already in flight until the stream has been cleaned
up. This also allows any pending write to
// complete.
- readUntil("The stream was not cleaned up", stream::isRecycled);
+ readUntil("The stream was not cleaned up", stream::isRecycleComplete);
// The stream was cancelled while sendfile was pending. It must still
be cleaned up.
Assert.assertEquals("Stream that was not recycled", 0,
countNotRecycled(Collections.singletonList(stream)));
@@ -838,7 +871,7 @@ public class TestHttp2Sendfile extends Http2TestBase {
private int countNotRecycled(Collection<Stream> streams) throws Exception {
long end = System.currentTimeMillis() + WAIT_LIMIT;
int notRecycled;
- while ((notRecycled = (int) streams.stream().filter(stream ->
!stream.isRecycled()).count()) > 0 &&
+ while ((notRecycled = (int) streams.stream().filter(stream ->
!stream.isRecycleComplete()).count()) > 0 &&
System.currentTimeMillis() < end) {
Thread.sleep(10);
}
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]