You are viewing a plain text version of this content. The canonical link for it is here.
Posted to notifications@asterixdb.apache.org by AsterixDB Code Review <do...@asterix-gerrit.ics.uci.edu> on 2026/08/13 18:12:06 UTC
[M] Change in asterixdb[trinity]: [NO ISSUE][HYR][NET] Bound the SSL handshake and stop it spinning
From Michael Blow <mb...@apache.org>:
Michael Blow has uploaded this change for review. ( https://asterix-gerrit.ics.uci.edu/c/asterixdb/+/21546?usp=email )
Change subject: [NO ISSUE][HYR][NET] Bound the SSL handshake and stop it spinning
......................................................................
[NO ISSUE][HYR][NET] Bound the SSL handshake and stop it spinning
- user model changes: no
- storage format changes: no
- interface changes: no
Details:
- IPCConnectionManager.register() puts the channel in non-blocking mode,
but SslHandshake.unwrap() was written as though it were blocking: a
read() returning 0 - the ordinary "peer has not sent anything yet"
case - fell through to engine.unwrap() on an empty buffer, yielded
BUFFER_UNDERFLOW, left the status at NEED_UNWRAP, and the loop in
handshake() retried immediately. A handshake waiting on its peer
therefore burned 100% of a core for as long as it waited; a thread
dump of a hung CI run showed 6383s of CPU over 6395s elapsed
- wait for readability on a private selector instead, at the two points
where more bytes are genuinely required: nothing buffered and nothing
read, and a partial record left by BUFFER_UNDERFLOW. Note the buffer
may still hold a complete record after a zero-length read, so waiting
unconditionally on read() == 0 would stall a handshake whose bytes had
already arrived
- bound the whole handshake by a deadline
(hyracks.ssl.handshake.timeout.sec, default 60). On expiry handshake()
returns false, which the connection manager already treats as a failed
handshake: it closes the handle, waitTillConnected() observes CLOSED,
and getIPCHandle() retries. Before this an unresponsive peer hung the
caller forever
- run the SSLEngine delegated tasks inline rather than on a
single-thread executor created per handshake and never shut down; the
handshake already runs on an executor thread of its own
Ext-ref: MB-73310
Co-Authored-By: Claude Opus 5 <no...@anthropic.com>
Change-Id: I50ffed3f912903663c4b67e713454b79e9d80503
---
M hyracks-fullstack/hyracks/hyracks-ipc/src/main/java/org/apache/hyracks/ipc/sockets/SslHandshake.java
A hyracks-fullstack/hyracks/hyracks-ipc/src/test/java/org/apache/hyracks/ipc/tests/SslHandshakeTimeoutTest.java
2 files changed, 169 insertions(+), 25 deletions(-)
git pull ssh://asterix-gerrit.ics.uci.edu:29418/asterixdb refs/changes/46/21546/1
diff --git a/hyracks-fullstack/hyracks/hyracks-ipc/src/main/java/org/apache/hyracks/ipc/sockets/SslHandshake.java b/hyracks-fullstack/hyracks/hyracks-ipc/src/main/java/org/apache/hyracks/ipc/sockets/SslHandshake.java
index fa4c8af..35fa121 100644
--- a/hyracks-fullstack/hyracks/hyracks-ipc/src/main/java/org/apache/hyracks/ipc/sockets/SslHandshake.java
+++ b/hyracks-fullstack/hyracks/hyracks-ipc/src/main/java/org/apache/hyracks/ipc/sockets/SslHandshake.java
@@ -20,19 +20,27 @@
import java.io.IOException;
import java.nio.ByteBuffer;
+import java.nio.channels.SelectionKey;
+import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
-import java.util.concurrent.ExecutorService;
-import java.util.concurrent.Executors;
+import java.util.concurrent.TimeUnit;
import javax.net.ssl.SSLEngine;
import javax.net.ssl.SSLEngineResult;
import javax.net.ssl.SSLException;
import org.apache.hyracks.util.NetworkUtil;
+import org.apache.hyracks.util.annotations.AiProvenance;
+import org.apache.logging.log4j.LogManager;
+import org.apache.logging.log4j.Logger;
public class SslHandshake {
- private final ExecutorService executor = Executors.newSingleThreadExecutor();
+ private static final Logger LOGGER = LogManager.getLogger();
+
+ public static final String HANDSHAKE_TIMEOUT_SEC_KEY = "hyracks.ssl.handshake.timeout.sec";
+ private static final int DEFAULT_HANDSHAKE_TIMEOUT_SEC = 60;
+
private final ByteBuffer handshakeOutData;
private final SocketChannel socketChannel;
private final SSLEngine engine;
@@ -40,6 +48,8 @@
private ByteBuffer handshakeInData;
private ByteBuffer outEncryptedData;
private ByteBuffer inEncryptedData;
+ private Selector readSelector;
+ private long deadlineNanos;
public SslHandshake(SslSocketChannel sslSocketChannel) {
socketChannel = sslSocketChannel.getSocketChannel();
@@ -53,29 +63,70 @@
handshakeInData = ByteBuffer.allocate(appBufferSize);
}
+ @AiProvenance(agent = AiProvenance.Agent.CLAUDE_OPUS_5, tool = AiProvenance.Tool.CLAUDE_CODE_UI, contributionKind = AiProvenance.ContributionKind.REFACTORED, notes = "handshake deadline, inline tasks")
public boolean handshake() throws IOException {
- handshakeStatus = engine.getHandshakeStatus();
- while (handshakeStatus != SSLEngineResult.HandshakeStatus.FINISHED
- && handshakeStatus != SSLEngineResult.HandshakeStatus.NOT_HANDSHAKING) {
- switch (handshakeStatus) {
- case NEED_UNWRAP:
- if (!unwrap()) {
- return false;
- }
- break;
- case NEED_WRAP:
- wrap();
- break;
- case NEED_TASK:
- Runnable task;
- while ((task = engine.getDelegatedTask()) != null) {
- executor.execute(task);
- }
- handshakeStatus = engine.getHandshakeStatus();
- break;
- default:
- throw new IllegalStateException("Invalid SSL handshake status: " + handshakeStatus);
+ // read per handshake rather than at class-init, so the bound can be adjusted at runtime
+ deadlineNanos = System.nanoTime() + TimeUnit.SECONDS
+ .toNanos(Integer.getInteger(HANDSHAKE_TIMEOUT_SEC_KEY, DEFAULT_HANDSHAKE_TIMEOUT_SEC));
+ try {
+ handshakeStatus = engine.getHandshakeStatus();
+ while (handshakeStatus != SSLEngineResult.HandshakeStatus.FINISHED
+ && handshakeStatus != SSLEngineResult.HandshakeStatus.NOT_HANDSHAKING) {
+ if (System.nanoTime() - deadlineNanos >= 0) {
+ LOGGER.warn("SSL handshake with {} timed out in state {}", socketChannel, handshakeStatus);
+ return false;
+ }
+ switch (handshakeStatus) {
+ case NEED_UNWRAP:
+ if (!unwrap()) {
+ return false;
+ }
+ break;
+ case NEED_WRAP:
+ wrap();
+ break;
+ case NEED_TASK:
+ Runnable task;
+ // run inline; the handshake already owns a thread of its own
+ while ((task = engine.getDelegatedTask()) != null) {
+ task.run();
+ }
+ handshakeStatus = engine.getHandshakeStatus();
+ break;
+ default:
+ throw new IllegalStateException("Invalid SSL handshake status: " + handshakeStatus);
+ }
}
+ return true;
+ } finally {
+ NetworkUtil.closeQuietly(readSelector);
+ }
+ }
+
+ /**
+ * Blocks until the channel has more data to be read, the handshake deadline expires, or the wait is
+ * interrupted. The channel is non-blocking, so without this a read returning zero would be retried
+ * immediately, spinning a core until the peer replies.
+ *
+ * @return true if the read should be retried, false if the handshake deadline has passed
+ */
+ @AiProvenance(agent = AiProvenance.Agent.CLAUDE_OPUS_5, tool = AiProvenance.Tool.CLAUDE_CODE_UI, contributionKind = AiProvenance.ContributionKind.GENERATED, notes = "await readability within deadline")
+ private boolean awaitReadable() throws IOException {
+ final long remainingNanos = deadlineNanos - System.nanoTime();
+ if (remainingNanos <= 0) {
+ LOGGER.warn("SSL handshake with {} timed out awaiting data", socketChannel);
+ return false;
+ }
+ if (readSelector == null) {
+ readSelector = Selector.open();
+ socketChannel.register(readSelector, SelectionKey.OP_READ);
+ }
+ // select() may return spuriously; the caller re-checks the deadline on the next pass
+ readSelector.select(Math.max(1, TimeUnit.NANOSECONDS.toMillis(remainingNanos)));
+ readSelector.selectedKeys().clear();
+ if (Thread.currentThread().isInterrupted()) {
+ LOGGER.warn("SSL handshake with {} interrupted awaiting data", socketChannel);
+ return false;
}
return true;
}
@@ -126,6 +177,10 @@
engine.closeOutbound();
return false;
}
+ if (read == 0 && inEncryptedData.position() == 0) {
+ // nothing buffered and nothing arrived; wait for the peer rather than spinning on the channel
+ return awaitReadable();
+ }
inEncryptedData.flip();
SSLEngineResult result;
try {
@@ -145,7 +200,8 @@
break;
case BUFFER_UNDERFLOW:
inEncryptedData = handleBufferUnderflow(engine, inEncryptedData);
- break;
+ // only a partial record is buffered; more bytes are needed before a retry can make progress
+ return awaitReadable();
case CLOSED:
if (engine.isOutboundDone()) {
return false;
diff --git a/hyracks-fullstack/hyracks/hyracks-ipc/src/test/java/org/apache/hyracks/ipc/tests/SslHandshakeTimeoutTest.java b/hyracks-fullstack/hyracks/hyracks-ipc/src/test/java/org/apache/hyracks/ipc/tests/SslHandshakeTimeoutTest.java
new file mode 100644
index 0000000..29d26d0
--- /dev/null
+++ b/hyracks-fullstack/hyracks/hyracks-ipc/src/test/java/org/apache/hyracks/ipc/tests/SslHandshakeTimeoutTest.java
@@ -0,0 +1,88 @@
+/*
+ * 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.hyracks.ipc.tests;
+
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+
+import java.lang.management.ManagementFactory;
+import java.lang.management.ThreadMXBean;
+import java.net.InetAddress;
+import java.net.InetSocketAddress;
+import java.nio.channels.ServerSocketChannel;
+import java.nio.channels.SocketChannel;
+import java.util.concurrent.TimeUnit;
+
+import javax.net.ssl.SSLContext;
+import javax.net.ssl.SSLEngine;
+
+import org.apache.hyracks.ipc.sockets.SslHandshake;
+import org.apache.hyracks.ipc.sockets.SslSocketChannel;
+import org.apache.hyracks.util.annotations.AiProvenance;
+import org.junit.Test;
+
+/**
+ * The IPC layer hands {@link SslHandshake} a non-blocking channel. A peer which accepts the connection
+ * and then says nothing must therefore make the handshake wait, and give up at its deadline, rather than
+ * retry the zero-length read in a tight loop.
+ */
+@AiProvenance(agent = AiProvenance.Agent.CLAUDE_OPUS_5, tool = AiProvenance.Tool.CLAUDE_CODE_UI, contributionKind = AiProvenance.ContributionKind.TEST_GENERATED, notes = "handshake deadline regression")
+public class SslHandshakeTimeoutTest {
+
+ private static final int TIMEOUT_SEC = 3;
+
+ @Test
+ public void unresponsivePeerFailsAtDeadlineWithoutSpinning() throws Exception {
+ final String previous = System.getProperty(SslHandshake.HANDSHAKE_TIMEOUT_SEC_KEY);
+ System.setProperty(SslHandshake.HANDSHAKE_TIMEOUT_SEC_KEY, String.valueOf(TIMEOUT_SEC));
+ try (ServerSocketChannel server = ServerSocketChannel.open()) {
+ server.bind(new InetSocketAddress(InetAddress.getLoopbackAddress(), 0));
+ try (SocketChannel client = SocketChannel.open(server.getLocalAddress());
+ // accepted, but deliberately never written to
+ SocketChannel accepted = server.accept()) {
+ client.configureBlocking(false);
+ final SSLEngine engine = SSLContext.getDefault().createSSLEngine();
+ engine.setUseClientMode(true);
+ final SslSocketChannel sslChannel = new SslSocketChannel(client, engine);
+
+ final ThreadMXBean threads = ManagementFactory.getThreadMXBean();
+ final long cpuStart = threads.getCurrentThreadCpuTime();
+ final long start = System.nanoTime();
+ final boolean handshakeSucceeded = sslChannel.handshake();
+ final long elapsedMillis = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - start);
+ final long cpuMillis = TimeUnit.NANOSECONDS.toMillis(threads.getCurrentThreadCpuTime() - cpuStart);
+
+ assertFalse("handshake should fail against a peer that never replies", handshakeSucceeded);
+ assertTrue("gave up after " + elapsedMillis + "ms, before the " + TIMEOUT_SEC + "s deadline",
+ elapsedMillis >= TimeUnit.SECONDS.toMillis(TIMEOUT_SEC) - 250);
+ assertTrue("still waiting after " + elapsedMillis + "ms, well past the deadline",
+ elapsedMillis < TimeUnit.SECONDS.toMillis(TIMEOUT_SEC) * 4);
+ // the point of the fix: the wait must be idle, not a retry loop on the non-blocking channel
+ assertTrue("handshake burned " + cpuMillis + "ms of CPU over " + elapsedMillis
+ + "ms of waiting; it is spinning rather than waiting", cpuMillis < elapsedMillis / 4);
+ }
+ } finally {
+ if (previous == null) {
+ System.clearProperty(SslHandshake.HANDSHAKE_TIMEOUT_SEC_KEY);
+ } else {
+ System.setProperty(SslHandshake.HANDSHAKE_TIMEOUT_SEC_KEY, previous);
+ }
+ }
+ }
+}
--
To view, visit https://asterix-gerrit.ics.uci.edu/c/asterixdb/+/21546?usp=email
To unsubscribe, or for help writing mail filters, visit https://asterix-gerrit.ics.uci.edu/settings?usp=email
Gerrit-MessageType: newchange
Gerrit-Project: asterixdb
Gerrit-Branch: trinity
Gerrit-Change-Id: I50ffed3f912903663c4b67e713454b79e9d80503
Gerrit-Change-Number: 21546
Gerrit-PatchSet: 1
Gerrit-Owner: Michael Blow <mb...@apache.org>