Repository navigation
Recover HTTP2 connection from half-open socket using pingInterval. #9444
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
joelc
wants to merge
11
commits into
lysine-dev:main
Choose a base branch
from
joelc:deadsocket-fix
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
11 commits
Select commit
Hold shift + click to select a range
792dcdc
Recover HTTP2 connection from half-open socket using pingInterval.
333d1ad
Pin alpine to 3
f6a4886
Preserve StreamResetException(PROTOCOL_ERROR) when pingInterval fails…
29df09b
Merge branch 'square:master' into deadsocket-fix
joelc 27c9b97
Merge branch 'master' into deadsocket-fix
joelc 6942ac6
Merge branch 'main' into deadsocket-fix
joelc 966e174
keep the caused-by exception when failConnection closes streams
joelc abef912
in failConnection, send GOAWAY before cancelling the socket
joelc f6f8ec7
gap - test that the ping interval unblocks a write stuck on a half-op…
joelc c26be5d
Merge remote-tracking branch 'origin/main' into deadsocket-fix
joelc 5d5e8be
Merge branch 'main' into deadsocket-fix
yschimke File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
211 changes: 211 additions & 0 deletions
211
container-tests/src/test/java/okhttp3/containers/DeadSocketTest.kt
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,211 @@ | ||
| /* | ||
| * Copyright (c) 2026 OkHttp Authors | ||
| * | ||
| * Licensed 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 okhttp3.containers | ||
|
|
||
| import assertk.assertFailure | ||
| import assertk.assertThat | ||
| import assertk.assertions.isInstanceOf | ||
| import assertk.assertions.isLessThan | ||
| import com.github.dockerjava.api.model.Capability | ||
| import java.io.IOException | ||
| import java.time.Duration | ||
| import java.util.concurrent.TimeUnit | ||
| import mockwebserver3.Dispatcher | ||
| import mockwebserver3.MockResponse | ||
| import mockwebserver3.MockWebServer | ||
| import mockwebserver3.RecordedRequest | ||
| import okhttp3.MediaType | ||
| import okhttp3.MediaType.Companion.toMediaType | ||
| import okhttp3.OkHttpClient | ||
| import okhttp3.Protocol | ||
| import okhttp3.Request | ||
| import okhttp3.RequestBody.Companion.toRequestBody | ||
| import okhttp3.Response | ||
| import okhttp3.tls.HandshakeCertificates | ||
| import okhttp3.tls.HeldCertificate | ||
| import org.junit.jupiter.api.AfterEach | ||
| import org.junit.jupiter.api.BeforeEach | ||
| import org.junit.jupiter.api.Test | ||
| import org.junit.jupiter.api.Timeout | ||
| import org.junit.jupiter.api.parallel.Isolated | ||
| import org.testcontainers.Testcontainers | ||
| import org.testcontainers.containers.GenericContainer | ||
| import org.testcontainers.containers.wait.strategy.Wait | ||
| import org.testcontainers.images.builder.ImageFromDockerfile | ||
|
|
||
| /** | ||
| * Reproduces a stateful firewall silently killing a pooled HTTP/2 connection at L3 (no RST, no FIN) | ||
| * while a new stream is being written. A socat tunnel in an Alpine container with `NET_ADMIN` | ||
| * engages `iptables -j DROP` mid-test, after which the next HEADERS write fills the kernel TCP | ||
| * send buffer and blocks indefinitely waiting for ACKs that will never arrive. | ||
| * | ||
| * Asserts the design intent of [OkHttpClient.Builder.pingInterval]: a configured ping interval | ||
| * detects the dead connection and fails the call within a small multiple of the interval. | ||
| * | ||
| * Requires Docker with the `NET_ADMIN` capability (for `iptables -j DROP`). | ||
| */ | ||
| @Isolated | ||
| @Timeout(value = 30, unit = TimeUnit.SECONDS) | ||
| class DeadSocketTest { | ||
| private lateinit var rootCa: HeldCertificate | ||
| private lateinit var mockWebServer: MockWebServer | ||
| private lateinit var tunnel: GenericContainer<*> | ||
| private lateinit var client: OkHttpClient | ||
|
|
||
| @BeforeEach | ||
| fun setUp() { | ||
| rootCa = | ||
| HeldCertificate | ||
| .Builder() | ||
| .certificateAuthority(0) | ||
| .build() | ||
|
|
||
| val serverCert = | ||
| HeldCertificate | ||
| .Builder() | ||
| .addSubjectAlternativeName("localhost") | ||
| .signedBy(rootCa) | ||
| .build() | ||
|
|
||
| val serverHandshakeCerts = | ||
| HandshakeCertificates | ||
| .Builder() | ||
| .heldCertificate(serverCert) | ||
| .build() | ||
|
|
||
| mockWebServer = MockWebServer() | ||
| mockWebServer.useHttps(serverHandshakeCerts.sslSocketFactory()) | ||
| mockWebServer.protocols = listOf(Protocol.HTTP_2, Protocol.HTTP_1_1) | ||
| mockWebServer.dispatcher = | ||
| object : Dispatcher() { | ||
| override fun dispatch(request: RecordedRequest): MockResponse = | ||
| MockResponse | ||
| .Builder() | ||
| .code(200) | ||
| .body("ok") | ||
| .build() | ||
| } | ||
| mockWebServer.start() | ||
|
|
||
| Testcontainers.exposeHostPorts(mockWebServer.port) | ||
|
|
||
| tunnel = | ||
| GenericContainer( | ||
| ImageFromDockerfile() | ||
| .withDockerfileFromBuilder { builder -> | ||
| builder | ||
| .from("alpine:3") | ||
| .run("apk add --no-cache socat iptables") | ||
| .build() | ||
| }, | ||
| ).withCreateContainerCmdModifier { cmd -> | ||
| cmd.hostConfig!!.withCapAdd(Capability.NET_ADMIN) | ||
| }.withExposedPorts(TUNNEL_PORT) | ||
| .withCommand( | ||
| "socat", | ||
| "TCP-LISTEN:$TUNNEL_PORT,fork,reuseaddr", | ||
| "TCP:host.testcontainers.internal:${mockWebServer.port}", | ||
| ).waitingFor(Wait.forListeningPort()) | ||
| tunnel.start() | ||
|
|
||
| val clientCerts = | ||
| HandshakeCertificates | ||
| .Builder() | ||
| .addTrustedCertificate(rootCa.certificate) | ||
| .build() | ||
|
|
||
| client = | ||
| OkHttpClient | ||
| .Builder() | ||
| .protocols(listOf(Protocol.HTTP_2, Protocol.HTTP_1_1)) | ||
| .pingInterval(Duration.ofSeconds(1)) | ||
| // Isolate pingInterval detection latency from connect-retry latency: with retry on, the | ||
| // retry's new TCP+TLS handshake races against connectTimeout through the still-dead tunnel | ||
| // and would dominate the measured elapsed time. | ||
| .retryOnConnectionFailure(false) | ||
| .sslSocketFactory(clientCerts.sslSocketFactory(), clientCerts.trustManager) | ||
| .hostnameVerifier { hostname, _ -> hostname == "localhost" } | ||
| .build() | ||
| } | ||
|
|
||
| @AfterEach | ||
| fun tearDown() { | ||
| client.connectionPool.evictAll() | ||
| client.dispatcher.executorService.shutdown() | ||
| mockWebServer.close() | ||
| tunnel.stop() | ||
| } | ||
|
|
||
| /** | ||
| * Warms up a pooled HTTP/2 connection through a socat tunnel, then engages `iptables -j DROP` to | ||
| * silently kill the connection at L3. The next request carries oversized headers so the HEADERS | ||
| * write overflows the TCP send buffer and blocks. The 1s pingInterval should detect the dead | ||
| * connection within a few intervals. | ||
| */ | ||
| @Test | ||
| fun pingIntervalBoundsFailureOnDeadConnection() { | ||
| repeat(3) { i -> | ||
| sendPost("warmup-$i").use { response -> | ||
| check(response.code == 200) { "warm-up $i failed: ${response.code}" } | ||
| response.body.string() | ||
| } | ||
| } | ||
|
|
||
| execInTunnel("iptables", "-I", "INPUT", "-p", "tcp", "--dport", "$TUNNEL_PORT", "-j", "DROP") | ||
| execInTunnel("iptables", "-I", "OUTPUT", "-p", "tcp", "--sport", "$TUNNEL_PORT", "-j", "DROP") | ||
|
|
||
| val startNanos = System.nanoTime() | ||
| assertFailure { | ||
| sendPostWithLargeHeaders().use { it.body.string() } | ||
| }.isInstanceOf<IOException>() | ||
| val elapsedSeconds = (System.nanoTime() - startNanos) / 1_000_000_000.0 | ||
|
|
||
| // pingInterval is 1s; design intent is failure within a small multiple of the interval. | ||
| assertThat(elapsedSeconds).isLessThan(3.0) | ||
| } | ||
|
|
||
| private fun sendPost(body: String): Response = | ||
| client | ||
| .newCall( | ||
| Request | ||
| .Builder() | ||
| .url("https://localhost:${tunnel.getMappedPort(TUNNEL_PORT)}/echo") | ||
| .post(body.toRequestBody(JSON)) | ||
| .build(), | ||
| ).execute() | ||
|
|
||
| private fun sendPostWithLargeHeaders(): Response = | ||
| client | ||
| .newCall( | ||
| Request | ||
| .Builder() | ||
| .url("https://localhost:${tunnel.getMappedPort(TUNNEL_PORT)}/echo") | ||
| .post("hello".toRequestBody(JSON)) | ||
| .header("X-Padding", "X".repeat(LARGE_HEADER_SIZE)) | ||
| .build(), | ||
| ).execute() | ||
|
|
||
| private fun execInTunnel(vararg command: String) { | ||
| val result = tunnel.execInContainer(*command) | ||
| check(result.exitCode == 0) { "container exec failed: ${result.stderr}" } | ||
| } | ||
|
|
||
| companion object { | ||
| private const val TUNNEL_PORT = 8443 | ||
| private const val LARGE_HEADER_SIZE = 8 * 1024 * 1024 | ||
| private val JSON: MediaType = "application/json".toMediaType() | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -85,6 +85,19 @@ class Http2Connection internal constructor( | |
| /** Asynchronously writes frames to the outgoing socket. */ | ||
| private val writerQueue = taskRunner.newQueue() | ||
|
|
||
| /** | ||
| * Runs the periodic pingInterval watchdog. Separate from [writerQueue] so missing-pong detection | ||
| * still fires when the writer is wedged on a frame write to a half-open connection. | ||
| */ | ||
| private val pingQueue = taskRunner.newQueue() | ||
|
|
||
| /** | ||
| * Runs the fallback that cancels the socket when a failed connection could not be closed | ||
| * gracefully. Separate from [pingQueue] and [writerQueue] because the thread that fails the | ||
| * connection can be one of their threads, and it blocks while it waits for the writer. | ||
| */ | ||
| private val cancelQueue = taskRunner.newQueue() | ||
|
|
||
| /** Ensures push promise callbacks events are sent in order per stream. */ | ||
| private val pushQueue = taskRunner.newQueue() | ||
|
|
||
|
|
@@ -147,7 +160,7 @@ class Http2Connection internal constructor( | |
| init { | ||
| if (builder.pingIntervalMillis != 0) { | ||
| val pingIntervalNanos = TimeUnit.MILLISECONDS.toNanos(builder.pingIntervalMillis.toLong()) | ||
| writerQueue.schedule("$connectionName ping", pingIntervalNanos) { | ||
| pingQueue.schedule("$connectionName ping", pingIntervalNanos) { | ||
| val failDueToMissingPong = | ||
| withLock { | ||
| if (intervalPongsReceived < intervalPingsSent) { | ||
|
|
@@ -161,7 +174,12 @@ class Http2Connection internal constructor( | |
| failConnection(null) | ||
| return@schedule -1L | ||
| } else { | ||
| writePing(false, INTERVAL_PING, 0) | ||
| // Fire-and-forget the ping write so the watchdog returns promptly. If writer.lock is | ||
| // held by a wedged frame write, the ping queues behind it; the next tick sees | ||
| // pongs < pings and fails the connection, which cancels the socket and unblocks the writer. | ||
| writerQueue.execute("$connectionName ping write") { | ||
| writePing(false, INTERVAL_PING, 0) | ||
| } | ||
| return@schedule pingIntervalNanos | ||
| } | ||
| } | ||
|
|
@@ -481,11 +499,41 @@ class Http2Connection internal constructor( | |
|
|
||
| // Release the threads. | ||
| writerQueue.shutdown() | ||
| pingQueue.shutdown() | ||
| cancelQueue.shutdown() | ||
| pushQueue.shutdown() | ||
| settingsListenerQueue.shutdown() | ||
| } | ||
|
|
||
| private fun failConnection(e: IOException?) { | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Maybe not a blocker and maybe not a huge concern, but this async work does feel racy, so I wonder if certain classes of errors might surface in two different ways now. |
||
| // Mark active streams with PROTOCOL_ERROR before the socket is cancelled so the caller surfaces | ||
| // StreamResetException(PROTOCOL_ERROR), or [e], on its waiting read or write. | ||
| // | ||
| // Note that if we cancel first: the reader thread's blocked socket read returns SocketException, | ||
| // which can reach the caller before close() -> stream.close() sets errorCode in Http2Stream.closeInternal. | ||
| // | ||
| // We use closeLater() (which enqueues RST_STREAM via writerQueue) rather than close(): the latter | ||
| // writes RST_STREAM synchronously under writer.lock, and that lock is already held by the | ||
| // frame write that's blocked on the half-open socket. See pingQueue. | ||
| val streamsToClose: Array<Http2Stream>? = | ||
| withLock { | ||
| if (streams.isNotEmpty()) streams.values.toTypedArray() else null | ||
| } | ||
| streamsToClose?.forEach { stream -> | ||
| stream.closeLater(ErrorCode.PROTOCOL_ERROR, e) | ||
| } | ||
|
|
||
| // close() sends the peer a GOAWAY frame, and it does so while holding writer.lock. If another | ||
| // thread is blocked writing to a half-open socket, that thread holds the lock and the GOAWAY | ||
| // cannot be sent. So arrange for the socket to be cancelled after a short delay: the blocked | ||
| // write then fails and releases the lock. If close() finishes first, it shuts down cancelQueue | ||
| // and the cancel never runs. | ||
| cancelQueue.schedule("$connectionName cancel socket", FAIL_CONNECTION_CANCEL_DELAY_NS) { | ||
| ignoreIoExceptions { | ||
| socket.cancel() | ||
| } | ||
| return@schedule -1L | ||
| } | ||
| close(ErrorCode.PROTOCOL_ERROR, ErrorCode.PROTOCOL_ERROR, e) | ||
| } | ||
|
|
||
|
|
@@ -1050,5 +1098,6 @@ class Http2Connection internal constructor( | |
| const val DEGRADED_PING = 2 | ||
| const val AWAIT_PING = 3 | ||
| const val DEGRADED_PONG_TIMEOUT_NS = 1_000_000_000 // 1 second. | ||
| const val FAIL_CONNECTION_CANCEL_DELAY_NS = 500_000_000L // 0.5 seconds. | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
These no longer run, they were moved out to keep CI focused.
#9736