diff --git a/httpcore5-h2/src/main/java/org/apache/hc/core5/http2/impl/nio/AbstractH2StreamMultiplexer.java b/httpcore5-h2/src/main/java/org/apache/hc/core5/http2/impl/nio/AbstractH2StreamMultiplexer.java index 63cdcc4a51..ced763b499 100644 --- a/httpcore5-h2/src/main/java/org/apache/hc/core5/http2/impl/nio/AbstractH2StreamMultiplexer.java +++ b/httpcore5-h2/src/main/java/org/apache/hc/core5/http2/impl/nio/AbstractH2StreamMultiplexer.java @@ -108,6 +108,11 @@ abstract class AbstractH2StreamMultiplexer implements Identifiable, HttpConnecti private static final long CONNECTION_WINDOW_LOW_MARK = 10 * 1024 * 1024; + // The GOAWAY probe needs one round trip only. The bound keeps its expiry, which the I/O + // reactor reports no sooner than its next timeout check, well within the five seconds + // a graceful reactor shutdown grants before it terminates the remaining sessions. + private static final Timeout MAX_GRACEFUL_SHUTDOWN_PING_TIMEOUT = Timeout.ofSeconds(1); + enum ConnectionHandshake { READY, ACTIVE, GRACEFUL_SHUTDOWN, SHUTDOWN } enum SettingsHandshake { READY, TRANSMITTED, ACKED } @@ -129,6 +134,15 @@ enum SettingsHandshake { READY, TRANSMITTED, ACKED } private final AtomicInteger connOutputWindow; private final AtomicInteger outputRequests; private final H2StreamListener streamListener; + private final boolean serverSide; + + // A server sends an initial GOAWAY before determining its final last-stream-id. + private final Timeout gracefulShutdownPingTimeout; + private boolean gracefulShutdownAwaitingPing; + private boolean gracefulShutdownPingAcknowledged; + private long gracefulShutdownPingStartedNanos; + // Session timeout to restore once the GOAWAY probe is over. + private Timeout gracefulShutdownSocketTimeout; private ConnectionHandshake connState = ConnectionHandshake.READY; private SettingsHandshake localSettingState = SettingsHandshake.READY; @@ -210,6 +224,8 @@ enum SettingsHandshake { READY, TRANSMITTED, ACKED } this.httpProcessor = Args.notNull(httpProcessor, "HTTP processor"); this.frameLimitController = Args.notNull(frameLimitController, "Frame limit controller"); this.streams = new H2Streams(idGenerator, this.frameLimitController); + // Server-generated stream IDs are even (RFC 9113, section 5.1.1). + this.serverSide = idGenerator.isSameSide(2); this.localConfig = h2Config != null ? h2Config : H2Config.DEFAULT; this.inputMetrics = new BasicH2TransportMetrics(); this.outputMetrics = new BasicH2TransportMetrics(); @@ -234,6 +250,8 @@ enum SettingsHandshake { READY, TRANSMITTED, ACKED } this.lastActivityTime = System.currentTimeMillis(); this.validateAfterInactivity = validateAfterInactivity; this.pingAckTimeout = Args.notNull(pingAckTimeout, "PING ACK timeout"); + this.gracefulShutdownPingTimeout = this.pingAckTimeout.compareTo(MAX_GRACEFUL_SHUTDOWN_PING_TIMEOUT) > 0 ? + MAX_GRACEFUL_SHUTDOWN_PING_TIMEOUT : this.pingAckTimeout; } @Override @@ -490,6 +508,9 @@ public final void onConnect() throws HttpException, IOException { } public final void onInput(final ByteBuffer src) throws HttpException, IOException { + if (gracefulShutdownDeadlineReached()) { + completeGracefulShutdown(); + } if (connState == ConnectionHandshake.SHUTDOWN) { ioSession.clearEvent(SelectionKey.OP_READ); } else { @@ -519,6 +540,10 @@ public final void onInput(final ByteBuffer src) throws HttpException, IOExceptio } public final void onOutput() throws HttpException, IOException { + if (gracefulShutdownAwaitingPing + && (gracefulShutdownPingAcknowledged || gracefulShutdownDeadlineReached())) { + completeGracefulShutdown(); + } ioSession.getLock().lock(); try { if (!outputBuffer.isEmpty()) { @@ -673,6 +698,14 @@ public final void onOutput() throws HttpException, IOException { } public final void onTimeout(final Timeout timeout) throws HttpException, IOException { + if (gracefulShutdownAwaitingPing && !gracefulShutdownPingTimeout.isDisabled()) { + // The session timeout has been shortened to bound the GOAWAY probe. Its expiry + // ends the probe and does not mean that the connection has been idle for too long. + completeGracefulShutdown(); + return; + } + gracefulShutdownAwaitingPing = false; + gracefulShutdownPingAcknowledged = false; connState = ConnectionHandshake.SHUTDOWN; final RawFrame goAway; @@ -692,6 +725,8 @@ public final void onTimeout(final Timeout timeout) throws HttpException, IOExcep } public final void onDisconnect() { + gracefulShutdownAwaitingPing = false; + gracefulShutdownPingAcknowledged = false; for (;;) { final AsyncPingHandler pingHandler = pingHandlers.poll(); if (pingHandler != null) { @@ -706,10 +741,31 @@ public final void onDisconnect() { private void executeShutdown(final ShutdownCommand shutdownCommand) throws IOException { if (shutdownCommand.getType() == CloseMode.IMMEDIATE) { + endGracefulShutdownProbe(); streams.shutdownAndReleaseAll(); connState = ConnectionHandshake.SHUTDOWN; - } else { - if (connState.compareTo(ConnectionHandshake.ACTIVE) <= 0) { + } else if (connState.compareTo(ConnectionHandshake.ACTIVE) <= 0 && !gracefulShutdownAwaitingPing) { + if (serverSide) { + // RFC 9113, section 6.8: announce shutdown first, then allow one RTT + // for requests that were already in flight before fixing last-stream-id. + final RawFrame goAway = frameFactory.createGoAway(Integer.MAX_VALUE, H2Error.NO_ERROR, "Graceful shutdown"); + commitFrame(goAway); + gracefulShutdownAwaitingPing = true; + gracefulShutdownPingStartedNanos = System.nanoTime(); + if (!gracefulShutdownPingTimeout.isDisabled()) { + // A silent peer generates no I/O events. The session timeout is the only + // timer the I/O reactor provides, so it bounds the probe until it is over. + gracefulShutdownSocketTimeout = ioSession.getSocketTimeout(); + ioSession.setSocketTimeout(gracefulShutdownPingTimeout); + } + executePing(new PingCommand(new BasicPingHandler(result -> { + if (result && gracefulShutdownAwaitingPing) { + gracefulShutdownPingAcknowledged = true; + requestSessionOutput(); + } + }))); + } else { + // Client-side shutdown keeps its existing single-GOAWAY behavior. final RawFrame goAway = frameFactory.createGoAway(streams.getLastRemoteId(), H2Error.NO_ERROR, "Graceful shutdown"); commitFrame(goAway); connState = streams.isEmpty() ? ConnectionHandshake.SHUTDOWN : ConnectionHandshake.GRACEFUL_SHUTDOWN; @@ -717,6 +773,28 @@ private void executeShutdown(final ShutdownCommand shutdownCommand) throws IOExc } } + private boolean gracefulShutdownDeadlineReached() { + return gracefulShutdownAwaitingPing && !gracefulShutdownPingTimeout.isDisabled() + && System.nanoTime() - gracefulShutdownPingStartedNanos >= gracefulShutdownPingTimeout.toNanoseconds(); + } + + private void endGracefulShutdownProbe() { + if (gracefulShutdownAwaitingPing) { + gracefulShutdownAwaitingPing = false; + gracefulShutdownPingAcknowledged = false; + if (!gracefulShutdownPingTimeout.isDisabled()) { + ioSession.setSocketTimeout(gracefulShutdownSocketTimeout); + } + } + } + + private void completeGracefulShutdown() throws IOException { + endGracefulShutdownProbe(); + final RawFrame goAway = frameFactory.createGoAway(streams.getLastRemoteId(), H2Error.NO_ERROR, "Graceful shutdown"); + commitFrame(goAway); + connState = streams.isEmpty() ? ConnectionHandshake.SHUTDOWN : ConnectionHandshake.GRACEFUL_SHUTDOWN; + } + private void executePing(final PingCommand pingCommand) throws IOException { final AsyncPingHandler handler = pingCommand.getHandler(); pingHandlers.add(handler); diff --git a/httpcore5-h2/src/test/java/org/apache/hc/core5/http2/impl/nio/TestAbstractH2StreamMultiplexer.java b/httpcore5-h2/src/test/java/org/apache/hc/core5/http2/impl/nio/TestAbstractH2StreamMultiplexer.java index 4a15429dd0..fee8a4f9c8 100644 --- a/httpcore5-h2/src/test/java/org/apache/hc/core5/http2/impl/nio/TestAbstractH2StreamMultiplexer.java +++ b/httpcore5-h2/src/test/java/org/apache/hc/core5/http2/impl/nio/TestAbstractH2StreamMultiplexer.java @@ -83,6 +83,7 @@ import org.mockito.ArgumentCaptor; import org.mockito.ArgumentMatchers; import org.mockito.Captor; +import org.mockito.InOrder; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.junit.jupiter.MockitoExtension; @@ -1626,6 +1627,360 @@ void testInputUnknownFrameTypeIgnored() throws Exception { Assertions.assertThatCode(() -> streamMultiplexer.onInput(ByteBuffer.wrap(writableChannel.toByteArray()))).doesNotThrowAnyException(); } + + // RFC 9113 section 6.8: the server first announces the maximum stream ID, + // then waits for an RTT probe ACK before sending the actual last-stream-id. + @Test + void testServerGracefulShutdownSendsTwoGoAwayFrames() throws Exception { + final List writes = new ArrayList<>(); + Mockito.when(protocolIOSession.write(ArgumentMatchers.any(ByteBuffer.class))) + .thenAnswer(inv -> { + final ByteBuffer buffer = inv.getArgument(0, ByteBuffer.class); + final byte[] copy = new byte[buffer.remaining()]; + buffer.get(copy); + writes.add(copy); + return copy.length; + }); + Mockito.when(protocolIOSession.poll()).thenReturn( + org.apache.hc.core5.http.nio.command.ShutdownCommand.GRACEFUL, null); + final Timeout socketTimeout = Timeout.ofSeconds(30); + Mockito.when(protocolIOSession.getSocketTimeout()).thenReturn(socketTimeout); + + final H2StreamMultiplexerImpl mux = new H2StreamMultiplexerImpl( + protocolIOSession, FRAME_FACTORY, StreamIdGenerator.EVEN, + httpProcessor, CharCodingConfig.DEFAULT, H2Config.DEFAULT, + h2StreamListener, () -> streamHandler); + mux.onConnect(); + completeSettingsHandshake(mux); + writes.clear(); + + mux.onOutput(); + final List firstFrames = parseFrames(concat(writes)); + final List firstGoAway = firstFrames.stream().filter(FrameStub::isGoAway) + .collect(java.util.stream.Collectors.toList()); + Assertions.assertThat(firstGoAway.size()).isEqualTo(1); + Assertions.assertThat(ByteBuffer.wrap(firstGoAway.get(0).payload).getInt() & Integer.MAX_VALUE) + .isEqualTo(Integer.MAX_VALUE); + final FrameStub ping = firstFrames.stream().filter(f -> f.isPing() && !f.isAck()) + .findFirst().orElseThrow(AssertionError::new); + Assertions.assertThat(mux.isOpen()).withFailMessage("Server must accept in-flight streams until RTT barrier").isTrue(); + // The session timeout is the only timer available to bound the probe. + Mockito.verify(protocolIOSession).setSocketTimeout(ArgumentMatchers.eq(Timeout.ofSeconds(1))); + Mockito.verify(protocolIOSession, Mockito.never()).setSocketTimeout(ArgumentMatchers.eq(socketTimeout)); + + // Simulate an in-flight peer stream reaching the server after the first GOAWAY. + final H2StreamChannel channel = mux.createChannel(1); + mux.createStream(channel, streamHandler); + + feedFrame(mux, new RawFrame(FrameType.PING.getValue(), FrameFlag.ACK.getValue(), + 0, ByteBuffer.wrap(ping.payload))); + mux.onOutput(); + final List finalGoAway = parseFrames(concat(writes)).stream() + .filter(FrameStub::isGoAway).collect(java.util.stream.Collectors.toList()); + Assertions.assertThat(finalGoAway.size()).isEqualTo(2); + Assertions.assertThat(ByteBuffer.wrap(finalGoAway.get(1).payload).getInt() & Integer.MAX_VALUE) + .isEqualTo(1); + Assertions.assertThat(mux.isOpen()).isFalse(); + Mockito.verify(protocolIOSession).setSocketTimeout(ArgumentMatchers.eq(socketTimeout)); + } + + @Test + void testClientGracefulShutdownStillUsesSingleGoAway() throws Exception { + final List writes = new ArrayList<>(); + Mockito.when(protocolIOSession.write(ArgumentMatchers.any(ByteBuffer.class))) + .thenAnswer(inv -> { + final ByteBuffer buffer = inv.getArgument(0, ByteBuffer.class); + final byte[] copy = new byte[buffer.remaining()]; + buffer.get(copy); + writes.add(copy); + return copy.length; + }); + Mockito.when(protocolIOSession.poll()).thenReturn( + org.apache.hc.core5.http.nio.command.ShutdownCommand.GRACEFUL, null); + + final H2StreamMultiplexerImpl mux = new H2StreamMultiplexerImpl( + protocolIOSession, FRAME_FACTORY, StreamIdGenerator.ODD, + httpProcessor, CharCodingConfig.DEFAULT, H2Config.DEFAULT, + h2StreamListener, () -> streamHandler); + mux.onConnect(); + completeSettingsHandshake(mux); + writes.clear(); + + mux.onOutput(); + final List frames = parseFrames(concat(writes)); + Assertions.assertThat(frames.stream().filter(FrameStub::isGoAway).count()).isEqualTo(1); + Assertions.assertThat(frames.stream().anyMatch(f -> f.isPing() && !f.isAck())).isFalse(); + } + + @Test + void testServerGracefulShutdownDeadlineOnOutputSendsFinalGoAway() throws Exception { + final List writes = new ArrayList<>(); + Mockito.when(protocolIOSession.write(ArgumentMatchers.any(ByteBuffer.class))) + .thenAnswer(inv -> { + final ByteBuffer buffer = inv.getArgument(0, ByteBuffer.class); + final byte[] copy = new byte[buffer.remaining()]; + buffer.get(copy); + writes.add(copy); + return copy.length; + }); + Mockito.when(protocolIOSession.poll()).thenReturn( + org.apache.hc.core5.http.nio.command.ShutdownCommand.GRACEFUL, null); + final Timeout socketTimeout = Timeout.ofSeconds(30); + Mockito.when(protocolIOSession.getSocketTimeout()).thenReturn(socketTimeout); + final H2StreamMultiplexerImpl mux = new H2StreamMultiplexerImpl( + protocolIOSession, FRAME_FACTORY, StreamIdGenerator.EVEN, + httpProcessor, CharCodingConfig.DEFAULT, H2Config.DEFAULT, + h2StreamListener, () -> streamHandler, null, Timeout.ofNanoseconds(1)); + mux.onConnect(); + completeSettingsHandshake(mux); + writes.clear(); + + mux.onOutput(); + final H2Stream active = mux.createStream(mux.createChannel(1), streamHandler); + Assertions.assertThat(active.isActive()).isTrue(); + // An I/O event past the monotonic deadline ends the probe even though + // the shortened session timeout has not fired. + mux.onOutput(); + + final List goAways = parseFrames(concat(writes)).stream() + .filter(FrameStub::isGoAway) + .collect(java.util.stream.Collectors.toList()); + Assertions.assertThat(goAways.size()).isEqualTo(2); + Assertions.assertThat(ByteBuffer.wrap(goAways.get(0).payload).getInt() & Integer.MAX_VALUE) + .isEqualTo(Integer.MAX_VALUE); + Assertions.assertThat(ByteBuffer.wrap(goAways.get(1).payload).getInt() & Integer.MAX_VALUE) + .isEqualTo(1); + Assertions.assertThat(active.isActive()).withFailMessage("Accepted requests must survive probe expiry").isTrue(); + Assertions.assertThat(mux.isOpen()).isFalse(); + final InOrder inOrder = Mockito.inOrder(protocolIOSession); + inOrder.verify(protocolIOSession).setSocketTimeout(ArgumentMatchers.eq(Timeout.ofNanoseconds(1))); + inOrder.verify(protocolIOSession).setSocketTimeout(ArgumentMatchers.eq(socketTimeout)); + } + + @Test + void testServerGracefulShutdownInvalidPingAckDoesNotComplete() throws Exception { + final List writes = new ArrayList<>(); + Mockito.when(protocolIOSession.write(ArgumentMatchers.any(ByteBuffer.class))) + .thenAnswer(inv -> { + final ByteBuffer buffer = inv.getArgument(0, ByteBuffer.class); + final byte[] copy = new byte[buffer.remaining()]; + buffer.get(copy); + writes.add(copy); + return copy.length; + }); + Mockito.when(protocolIOSession.poll()).thenReturn( + org.apache.hc.core5.http.nio.command.ShutdownCommand.GRACEFUL, null); + + final H2StreamMultiplexerImpl mux = new H2StreamMultiplexerImpl( + protocolIOSession, FRAME_FACTORY, StreamIdGenerator.EVEN, + httpProcessor, CharCodingConfig.DEFAULT, H2Config.DEFAULT, + h2StreamListener, () -> streamHandler); + mux.onConnect(); + completeSettingsHandshake(mux); + writes.clear(); + + mux.onOutput(); + final H2Stream active = mux.createStream(mux.createChannel(1), streamHandler); + feedFrame(mux, new RawFrame(FrameType.PING.getValue(), FrameFlag.ACK.getValue(), + 0, ByteBuffer.wrap(new byte[8]))); + mux.onOutput(); + Assertions.assertThat(parseFrames(concat(writes)).stream() + .filter(FrameStub::isGoAway).count()) + .withFailMessage("Wrong ACK must not finish the GOAWAY exchange before the deadline").isEqualTo(1L); + Assertions.assertThat(mux.isOpen()).isTrue(); + Assertions.assertThat(active.isActive()).isTrue(); + // The probe is still pending, so the shortened session timeout stays in place. + Mockito.verify(protocolIOSession).setSocketTimeout(ArgumentMatchers.eq(Timeout.ofSeconds(1))); + Mockito.verify(protocolIOSession, Mockito.times(1)).setSocketTimeout(ArgumentMatchers.any()); + } + + // A silent peer generates no I/O events. Expiry of the shortened session timeout ends the probe. + @Test + void testServerGracefulShutdownProbeTimeoutSendsFinalGoAway() throws Exception { + final List writes = captureWrites(); + Mockito.when(protocolIOSession.poll()).thenReturn( + org.apache.hc.core5.http.nio.command.ShutdownCommand.GRACEFUL, null); + final Timeout socketTimeout = Timeout.ofSeconds(30); + Mockito.when(protocolIOSession.getSocketTimeout()).thenReturn(socketTimeout); + final H2StreamMultiplexerImpl mux = newServerMux(Timeout.ofSeconds(5)); + mux.onConnect(); + completeSettingsHandshake(mux); + + mux.onOutput(); + final H2Stream active = mux.createStream(mux.createChannel(1), streamHandler); + writes.clear(); + mux.onTimeout(Timeout.ofSeconds(1)); + + final List goAways = goAways(writes); + Assertions.assertThat(goAways.size()).isEqualTo(1); + Assertions.assertThat(goAwayLastStreamId(goAways.get(0))).isEqualTo(1); + Assertions.assertThat(goAwayErrorCode(goAways.get(0))).isEqualTo(H2Error.NO_ERROR.getCode()); + Assertions.assertThat(goAwayDebugData(goAways.get(0))).isEqualTo("Graceful shutdown"); + Assertions.assertThat(active.isActive()).withFailMessage("Accepted requests must survive probe expiry").isTrue(); + Mockito.verify(streamHandler, Mockito.never()).failed(ArgumentMatchers.any()); + Assertions.assertThat(mux.isOpen()).isFalse(); + final InOrder inOrder = Mockito.inOrder(protocolIOSession); + inOrder.verify(protocolIOSession).setSocketTimeout(ArgumentMatchers.eq(Timeout.ofSeconds(1))); + inOrder.verify(protocolIOSession).setSocketTimeout(ArgumentMatchers.eq(socketTimeout)); + } + + @Test + void testServerGracefulShutdownProbeTimeoutClosesIdleConnection() throws Exception { + final List writes = captureWrites(); + Mockito.when(protocolIOSession.poll()).thenReturn( + org.apache.hc.core5.http.nio.command.ShutdownCommand.GRACEFUL, null); + final H2StreamMultiplexerImpl mux = newServerMux(Timeout.ofSeconds(5)); + mux.onConnect(); + completeSettingsHandshake(mux); + writes.clear(); + + mux.onOutput(); + mux.onTimeout(Timeout.ofSeconds(1)); + mux.onOutput(); + + final List goAways = goAways(writes); + Assertions.assertThat(goAways.size()).isEqualTo(2); + Assertions.assertThat(goAwayLastStreamId(goAways.get(0))).isEqualTo(Integer.MAX_VALUE); + Assertions.assertThat(goAwayLastStreamId(goAways.get(1))).isEqualTo(0); + // An inactivity-timeout GOAWAY also uses NO_ERROR; only the debug data tells it apart + // from the probe-expiry GOAWAY this test is meant to guard. + Assertions.assertThat(goAwayDebugData(goAways.get(1))).isEqualTo("Graceful shutdown"); + Mockito.verify(protocolIOSession).close(); + } + + // The peer may not have acknowledged local SETTINGS yet. Probe expiry is still not an error. + @Test + void testServerGracefulShutdownProbeTimeoutBeforeSettingsAck() throws Exception { + final List writes = captureWrites(); + Mockito.when(protocolIOSession.poll()).thenReturn( + org.apache.hc.core5.http.nio.command.ShutdownCommand.GRACEFUL, null); + final H2StreamMultiplexerImpl mux = newServerMux(Timeout.ofSeconds(5)); + mux.onConnect(); + feedFrame(mux, FRAME_FACTORY.createSettings(new H2Setting[] { + new H2Setting(H2Param.MAX_FRAME_SIZE, FrameConsts.MIN_FRAME_SIZE) + })); + + mux.onOutput(); + writes.clear(); + mux.onTimeout(Timeout.ofSeconds(1)); + + final List goAways = goAways(writes); + Assertions.assertThat(goAways.size()).isEqualTo(1); + Assertions.assertThat(goAwayErrorCode(goAways.get(0))).isEqualTo(H2Error.NO_ERROR.getCode()); + Assertions.assertThat(goAwayDebugData(goAways.get(0))).isEqualTo("Graceful shutdown"); + } + + @Test + void testServerGracefulShutdownInactivityTimeoutAfterProbeFailsStreams() throws Exception { + final List writes = captureWrites(); + Mockito.when(protocolIOSession.poll()).thenReturn( + org.apache.hc.core5.http.nio.command.ShutdownCommand.GRACEFUL, null); + final Timeout socketTimeout = Timeout.ofSeconds(30); + Mockito.when(protocolIOSession.getSocketTimeout()).thenReturn(socketTimeout); + final H2StreamMultiplexerImpl mux = newServerMux(Timeout.ofSeconds(5)); + mux.onConnect(); + completeSettingsHandshake(mux); + + mux.onOutput(); + final H2Stream active = mux.createStream(mux.createChannel(1), streamHandler); + mux.onTimeout(Timeout.ofSeconds(1)); + Assertions.assertThat(active.isActive()).isTrue(); + writes.clear(); + + // With the probe over the session timeout has its usual meaning again. + mux.onTimeout(socketTimeout); + + final List goAways = goAways(writes); + Assertions.assertThat(goAways.size()).isEqualTo(1); + Assertions.assertThat(goAwayDebugData(goAways.get(0))).startsWith("Timeout due to inactivity"); + Mockito.verify(streamHandler, Mockito.atLeastOnce()).failed(exceptionCaptor.capture()); + Assertions.assertThat(exceptionCaptor.getValue()).isInstanceOf(H2StreamResetException.class); + } + + // Without a PING ACK timeout the probe is unbounded and the session timeout is left alone. + @Test + void testServerGracefulShutdownWithoutPingAckTimeoutKeepsSocketTimeout() throws Exception { + final List writes = captureWrites(); + Mockito.when(protocolIOSession.poll()).thenReturn( + org.apache.hc.core5.http.nio.command.ShutdownCommand.GRACEFUL, null); + final H2StreamMultiplexerImpl mux = newServerMux(Timeout.DISABLED); + mux.onConnect(); + completeSettingsHandshake(mux); + + mux.onOutput(); + mux.createStream(mux.createChannel(1), streamHandler); + writes.clear(); + mux.onTimeout(Timeout.ofSeconds(30)); + + final List goAways = goAways(writes); + Assertions.assertThat(goAways.size()).isEqualTo(1); + Assertions.assertThat(goAwayDebugData(goAways.get(0))).startsWith("Timeout due to inactivity"); + Mockito.verify(streamHandler, Mockito.atLeastOnce()).failed(ArgumentMatchers.any()); + Assertions.assertThat(mux.isOpen()).isFalse(); + Mockito.verify(protocolIOSession, Mockito.never()).setSocketTimeout(ArgumentMatchers.any()); + } + + @Test + void testServerGracefulShutdownImmediateShutdownRestoresSocketTimeout() throws Exception { + final List writes = captureWrites(); + Mockito.when(protocolIOSession.poll()).thenReturn( + org.apache.hc.core5.http.nio.command.ShutdownCommand.GRACEFUL, + org.apache.hc.core5.http.nio.command.ShutdownCommand.IMMEDIATE, + null); + final Timeout socketTimeout = Timeout.ofSeconds(30); + Mockito.when(protocolIOSession.getSocketTimeout()).thenReturn(socketTimeout); + final H2StreamMultiplexerImpl mux = newServerMux(Timeout.ofSeconds(5)); + mux.onConnect(); + completeSettingsHandshake(mux); + writes.clear(); + + mux.onOutput(); + + Assertions.assertThat(goAways(writes).size()).isEqualTo(1); + final InOrder inOrder = Mockito.inOrder(protocolIOSession); + inOrder.verify(protocolIOSession).setSocketTimeout(ArgumentMatchers.eq(Timeout.ofSeconds(1))); + inOrder.verify(protocolIOSession).setSocketTimeout(ArgumentMatchers.eq(socketTimeout)); + Mockito.verify(protocolIOSession).close(); + } + + private List captureWrites() throws IOException { + final List writes = new ArrayList<>(); + Mockito.when(protocolIOSession.write(ArgumentMatchers.any(ByteBuffer.class))) + .thenAnswer(inv -> { + final ByteBuffer buffer = inv.getArgument(0, ByteBuffer.class); + final byte[] copy = new byte[buffer.remaining()]; + buffer.get(copy); + writes.add(copy); + return copy.length; + }); + return writes; + } + + private H2StreamMultiplexerImpl newServerMux(final Timeout pingAckTimeout) { + return new H2StreamMultiplexerImpl( + protocolIOSession, FRAME_FACTORY, StreamIdGenerator.EVEN, + httpProcessor, CharCodingConfig.DEFAULT, H2Config.DEFAULT, + h2StreamListener, () -> streamHandler, null, pingAckTimeout); + } + + private static List goAways(final List writes) { + return parseFrames(concat(writes)).stream() + .filter(FrameStub::isGoAway) + .collect(java.util.stream.Collectors.toList()); + } + + private static int goAwayLastStreamId(final FrameStub goAway) { + return ByteBuffer.wrap(goAway.payload).getInt() & Integer.MAX_VALUE; + } + + private static int goAwayErrorCode(final FrameStub goAway) { + return ByteBuffer.wrap(goAway.payload).getInt(4); + } + + private static String goAwayDebugData(final FrameStub goAway) { + return new String(goAway.payload, 8, goAway.payload.length - 8, StandardCharsets.US_ASCII); + } + private static byte[] encodeFrame(final RawFrame frame) throws IOException { final WritableByteChannelMock writableChannel = new WritableByteChannelMock(256); final FrameOutputBuffer outBuffer = new FrameOutputBuffer(16 * 1024); diff --git a/httpcore5-testing/src/test/java/org/apache/hc/core5/testing/nio/H2ServerGracefulShutdownTest.java b/httpcore5-testing/src/test/java/org/apache/hc/core5/testing/nio/H2ServerGracefulShutdownTest.java new file mode 100644 index 0000000000..f01252eaa0 --- /dev/null +++ b/httpcore5-testing/src/test/java/org/apache/hc/core5/testing/nio/H2ServerGracefulShutdownTest.java @@ -0,0 +1,420 @@ +/* + * ==================================================================== + * 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. + * ==================================================================== + * + * This software consists of voluntary contributions made by many + * individuals on behalf of the Apache Software Foundation. For more + * information on the Apache Software Foundation, please see + * . + * + */ + +package org.apache.hc.core5.testing.nio; + +import java.io.Closeable; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.net.InetAddress; +import java.net.InetSocketAddress; +import java.net.Socket; +import java.net.SocketException; +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; + +import org.apache.hc.core5.http.ConnectionClosedException; +import org.apache.hc.core5.http.URIScheme; +import org.apache.hc.core5.http.impl.bootstrap.HttpAsyncServer; +import org.apache.hc.core5.http.message.BasicHeader; +import org.apache.hc.core5.http2.H2Error; +import org.apache.hc.core5.http2.HttpVersionPolicy; +import org.apache.hc.core5.http2.config.H2Config; +import org.apache.hc.core5.http2.frame.DefaultFrameFactory; +import org.apache.hc.core5.http2.frame.FrameConsts; +import org.apache.hc.core5.http2.frame.FrameFactory; +import org.apache.hc.core5.http2.frame.FrameFlag; +import org.apache.hc.core5.http2.frame.FrameType; +import org.apache.hc.core5.http2.frame.RawFrame; +import org.apache.hc.core5.http2.hpack.HPackEncoder; +import org.apache.hc.core5.http2.impl.io.FrameInputBuffer; +import org.apache.hc.core5.http2.impl.io.FrameOutputBuffer; +import org.apache.hc.core5.io.CloseMode; +import org.apache.hc.core5.reactor.IOReactorConfig; +import org.apache.hc.core5.reactor.ListenerEndpoint; +import org.apache.hc.core5.testing.extension.nio.H2AsyncServerResource; +import org.apache.hc.core5.util.ByteArrayBuffer; +import org.apache.hc.core5.util.TimeValue; +import org.apache.hc.core5.util.Timeout; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; + +/** + * Two-phase graceful shutdown of an HTTP/2 server as seen by a frame level client. + * Unlike a regular HTTP/2 endpoint the client acknowledges PING frames only when told to, + * which makes it possible to play a peer that goes silent. + */ +class H2ServerGracefulShutdownTest { + + private static final FrameFactory FRAME_FACTORY = DefaultFrameFactory.INSTANCE; + private static final byte[] PREFACE = "PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n".getBytes(StandardCharsets.US_ASCII); + + // Far longer than the GOAWAY probe, so that only the probe can account for a timely shutdown. + private static final Timeout SERVER_SOCKET_TIMEOUT = Timeout.ofSeconds(30); + // Shorter than the server socket timeout. A GOAWAY caused by inactivity fails the read instead. + private static final Timeout CLIENT_SOCKET_TIMEOUT = Timeout.ofSeconds(15); + // A silent peer must be given time to acknowledge the PING. + private static final long MIN_PROBE_MILLIS = 500; + private static final long MAX_PROBE_MILLIS = 10000; + // I/O reactors terminate the remaining sessions five seconds into a graceful close. + private static final long REACTOR_GRACE_MILLIS = 5000; + + @RegisterExtension + private final H2AsyncServerResource serverResource; + + H2ServerGracefulShutdownTest() { + this.serverResource = new H2AsyncServerResource(); + this.serverResource.configure(bootstrap -> bootstrap + .setVersionPolicy(HttpVersionPolicy.FORCE_HTTP_2) + .setIOReactorConfig(IOReactorConfig.custom() + .setSoTimeout(SERVER_SOCKET_TIMEOUT) + .build()) + .register("*", () -> new SingleLineResponseHandler("OK"))); + } + + @Test + void testSilentPeerShutdown() throws Exception { + final HttpAsyncServer server = serverResource.start(); + try (final RawH2Client client = new RawH2Client(listen(server))) { + client.handshake(); + client.sendRequest(1, "GET", true); + client.awaitResponse(1); + + final long startNanos = System.nanoTime(); + server.initiateShutdown(); + + final List frames = new ArrayList<>(); + client.readUntilClosed(frames); + assertSilentPeerShutdown(frames, startNanos, 1, MAX_PROBE_MILLIS); + + server.awaitShutdown(TimeValue.ofSeconds(60)); + final long shutdownMillis = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNanos); + Assertions.assertTrue(shutdownMillis < MAX_PROBE_MILLIS, "Shutdown took " + shutdownMillis + " ms"); + } + } + + @Test + void testSilentPeerGracefulClose() throws Exception { + final HttpAsyncServer server = serverResource.start(); + try (final RawH2Client client = new RawH2Client(listen(server))) { + client.handshake(); + client.sendRequest(1, "GET", true); + client.awaitResponse(1); + + final long startNanos = System.nanoTime(); + final Thread closer = new Thread(() -> server.close(CloseMode.GRACEFUL), "server-close"); + closer.start(); + + final List frames = new ArrayList<>(); + client.readUntilClosed(frames); + closer.join(MAX_PROBE_MILLIS); + Assertions.assertFalse(closer.isAlive()); + // The final GOAWAY must beat the forced termination of the session. + assertSilentPeerShutdown(frames, startNanos, 1, REACTOR_GRACE_MILLIS); + } + } + + @Test + void testSilentPeerProbeTimeoutKeepsActiveStream() throws Exception { + final HttpAsyncServer server = serverResource.start(); + try (final RawH2Client client = new RawH2Client(listen(server))) { + client.handshake(); + // The message body is still pending, which keeps the stream open. + client.sendRequest(1, "POST", false); + client.sync(); + + final long startNanos = System.nanoTime(); + server.initiateShutdown(); + + final List frames = new ArrayList<>(); + client.readUntil(FrameType.GOAWAY, frames); + client.readUntil(FrameType.GOAWAY, frames); + assertSilentPeerShutdown(frames, startNanos, 1, MAX_PROBE_MILLIS); + + // Probe expiry must not have failed the stream accepted before the shutdown. + client.write(FRAME_FACTORY.createData(1, ByteBuffer.wrap(new byte[] {'x'}), true)); + frames.clear(); + client.readUntilClosed(frames); + assertStreamCompleted(frames, 1); + for (final ReceivedFrame frame : frames) { + Assertions.assertFalse(frame.isType(FrameType.GOAWAY), "Unexpected GOAWAY"); + } + server.awaitShutdown(TimeValue.ofSeconds(60)); + } + } + + @Test + void testRequestInFlightDuringShutdown() throws Exception { + final HttpAsyncServer server = serverResource.start(); + try (final RawH2Client client = new RawH2Client(listen(server))) { + client.handshake(); + client.sendRequest(1, "GET", true); + client.awaitResponse(1); + + server.initiateShutdown(); + + final List frames = new ArrayList<>(); + final ReceivedFrame initialGoAway = client.readUntil(FrameType.GOAWAY, frames); + Assertions.assertEquals(Integer.MAX_VALUE, initialGoAway.goAwayLastStreamId()); + final ReceivedFrame ping = client.readUntil(FrameType.PING, frames); + Assertions.assertFalse(ping.isFlagSet(FrameFlag.ACK)); + + // A request that was on its way when the initial GOAWAY was sent, then the PING ACK. + client.sendRequest(3, "GET", true); + client.write(FRAME_FACTORY.createPingAck(ByteBuffer.wrap(ping.payload))); + + frames.clear(); + client.readUntilClosed(frames); + assertStreamCompleted(frames, 3); + final List goAways = new ArrayList<>(); + for (final ReceivedFrame frame : frames) { + if (frame.isType(FrameType.GOAWAY)) { + goAways.add(frame); + } + } + Assertions.assertEquals(1, goAways.size()); + assertFinalGoAway(goAways.get(0), 3); + server.awaitShutdown(TimeValue.ofSeconds(60)); + } + } + + private static InetSocketAddress listen(final HttpAsyncServer server) throws Exception { + final Future future = server.listen( + new InetSocketAddress(InetAddress.getLoopbackAddress(), 0), URIScheme.HTTP); + return (InetSocketAddress) future.get().getAddress(); + } + + private static void assertSilentPeerShutdown( + final List frames, + final long startNanos, + final int lastStreamId, + final long maxProbeMillis) { + final List control = new ArrayList<>(); + for (final ReceivedFrame frame : frames) { + if (frame.isType(FrameType.GOAWAY) || frame.isType(FrameType.PING)) { + control.add(frame); + } + } + Assertions.assertEquals(3, control.size(), "Expected GOAWAY, PING, GOAWAY"); + final ReceivedFrame initialGoAway = control.get(0); + Assertions.assertTrue(initialGoAway.isType(FrameType.GOAWAY)); + Assertions.assertEquals(Integer.MAX_VALUE, initialGoAway.goAwayLastStreamId()); + Assertions.assertEquals(H2Error.NO_ERROR.getCode(), initialGoAway.goAwayErrorCode()); + final ReceivedFrame ping = control.get(1); + Assertions.assertTrue(ping.isType(FrameType.PING)); + Assertions.assertFalse(ping.isFlagSet(FrameFlag.ACK)); + final ReceivedFrame finalGoAway = control.get(2); + assertFinalGoAway(finalGoAway, lastStreamId); + final long probeMillis = TimeUnit.NANOSECONDS.toMillis(finalGoAway.timeNanos - startNanos); + Assertions.assertTrue(probeMillis >= MIN_PROBE_MILLIS, "Final GOAWAY after " + probeMillis + " ms"); + Assertions.assertTrue(probeMillis < maxProbeMillis, "Final GOAWAY after " + probeMillis + " ms"); + } + + private static void assertFinalGoAway(final ReceivedFrame goAway, final int lastStreamId) { + Assertions.assertTrue(goAway.isType(FrameType.GOAWAY)); + Assertions.assertEquals(lastStreamId, goAway.goAwayLastStreamId()); + Assertions.assertEquals(H2Error.NO_ERROR.getCode(), goAway.goAwayErrorCode()); + // An inactivity timeout reports NO_ERROR as well. Only the debug data tells them apart. + Assertions.assertEquals("Graceful shutdown", goAway.goAwayDebugData()); + } + + private static void assertStreamCompleted(final List frames, final int streamId) { + boolean completed = false; + for (final ReceivedFrame frame : frames) { + if (frame.streamId == streamId) { + Assertions.assertFalse(frame.isType(FrameType.RST_STREAM), "Stream " + streamId + " has been reset"); + if (frame.isFlagSet(FrameFlag.END_STREAM) + && (frame.isType(FrameType.HEADERS) || frame.isType(FrameType.DATA))) { + completed = true; + } + } + } + Assertions.assertTrue(completed, "Stream " + streamId + " has not been completed"); + } + + private static final class ReceivedFrame { + + final int type; + final int flags; + final int streamId; + final byte[] payload; + final long timeNanos; + + ReceivedFrame(final int type, final int flags, final int streamId, final byte[] payload, final long timeNanos) { + this.type = type; + this.flags = flags; + this.streamId = streamId; + this.payload = payload; + this.timeNanos = timeNanos; + } + + boolean isType(final FrameType frameType) { + return type == frameType.getValue(); + } + + boolean isFlagSet(final FrameFlag flag) { + return (flags & flag.getValue()) != 0; + } + + int goAwayLastStreamId() { + return ByteBuffer.wrap(payload).getInt() & Integer.MAX_VALUE; + } + + int goAwayErrorCode() { + return ByteBuffer.wrap(payload).getInt(4); + } + + String goAwayDebugData() { + return new String(payload, 8, payload.length - 8, StandardCharsets.US_ASCII); + } + + } + + private static final class RawH2Client implements Closeable { + + private final Socket socket; + private final InputStream inputStream; + private final OutputStream outputStream; + private final FrameInputBuffer inputBuffer; + private final FrameOutputBuffer outputBuffer; + private final HPackEncoder hPackEncoder; + + RawH2Client(final InetSocketAddress address) throws IOException { + this.socket = new Socket(); + this.socket.setSoTimeout(CLIENT_SOCKET_TIMEOUT.toMillisecondsIntBound()); + this.socket.setTcpNoDelay(true); + this.socket.connect(address, CLIENT_SOCKET_TIMEOUT.toMillisecondsIntBound()); + this.inputStream = socket.getInputStream(); + this.outputStream = socket.getOutputStream(); + this.inputBuffer = new FrameInputBuffer(FrameConsts.MIN_FRAME_SIZE); + this.outputBuffer = new FrameOutputBuffer(FrameConsts.MIN_FRAME_SIZE); + this.hPackEncoder = new HPackEncoder(H2Config.INIT.getHeaderTableSize(), StandardCharsets.US_ASCII); + } + + void write(final RawFrame frame) throws IOException { + outputBuffer.write(frame, outputStream); + outputStream.flush(); + } + + ReceivedFrame read() throws IOException { + final RawFrame frame = inputBuffer.read(inputStream); + // The payload is a view of the input buffer and does not survive the next read. + final ByteBuffer payload = frame.getPayload(); + final byte[] content = new byte[payload != null ? payload.remaining() : 0]; + if (payload != null) { + payload.get(content); + } + return new ReceivedFrame(frame.getType(), frame.getFlags(), frame.getStreamId(), content, System.nanoTime()); + } + + void handshake() throws IOException { + outputStream.write(PREFACE); + write(FRAME_FACTORY.createSettings()); + boolean settingsReceived = false; + boolean settingsAcknowledged = false; + while (!settingsReceived || !settingsAcknowledged) { + final ReceivedFrame frame = read(); + if (frame.isType(FrameType.SETTINGS)) { + if (frame.isFlagSet(FrameFlag.ACK)) { + settingsAcknowledged = true; + } else { + write(FRAME_FACTORY.createSettingsAck()); + settingsReceived = true; + } + } + } + } + + void sendRequest(final int streamId, final String method, final boolean endStream) throws IOException { + final ByteArrayBuffer buffer = new ByteArrayBuffer(128); + hPackEncoder.encodeHeaders(buffer, Arrays.asList( + new BasicHeader(":method", method), + new BasicHeader(":scheme", "http"), + new BasicHeader(":authority", "localhost:" + socket.getPort()), + new BasicHeader(":path", "/")), false); + write(FRAME_FACTORY.createHeaders( + streamId, ByteBuffer.wrap(buffer.array(), 0, buffer.length()), true, endStream)); + } + + void awaitResponse(final int streamId) throws IOException { + for (;;) { + final ReceivedFrame frame = read(); + if (frame.streamId == streamId && frame.isFlagSet(FrameFlag.END_STREAM) + && (frame.isType(FrameType.HEADERS) || frame.isType(FrameType.DATA))) { + return; + } + } + } + + // A PING round trip. Its ACK proves the server has processed everything sent before it. + void sync() throws IOException { + write(FRAME_FACTORY.createPing(ByteBuffer.wrap(new byte[8]))); + for (;;) { + final ReceivedFrame frame = read(); + if (frame.isType(FrameType.PING) && frame.isFlagSet(FrameFlag.ACK)) { + return; + } + } + } + + ReceivedFrame readUntil(final FrameType frameType, final List frames) throws IOException { + for (;;) { + final ReceivedFrame frame = read(); + frames.add(frame); + if (frame.isType(frameType)) { + return frame; + } + } + } + + void readUntilClosed(final List frames) throws IOException { + for (;;) { + final ReceivedFrame frame; + try { + frame = read(); + } catch (final ConnectionClosedException | SocketException ex) { + return; + } + frames.add(frame); + } + } + + @Override + public void close() throws IOException { + socket.close(); + } + + } + +}