diff --git a/flight/flight-core/src/main/java/org/apache/arrow/flight/auth/ClientAuthWrapper.java b/flight/flight-core/src/main/java/org/apache/arrow/flight/auth/ClientAuthWrapper.java index 19d4f77a03..d3df09e6c9 100644 --- a/flight/flight-core/src/main/java/org/apache/arrow/flight/auth/ClientAuthWrapper.java +++ b/flight/flight-core/src/main/java/org/apache/arrow/flight/auth/ClientAuthWrapper.java @@ -63,6 +63,9 @@ public static void doClientAuth(ClientAuthHandler authHandler, FlightServiceStub private static class AuthObserver implements StreamObserver { + // Queued after the last message so a blocked reader wakes up when the server is done. + private static final byte[] END_OF_STREAM = new byte[0]; + private volatile StreamObserver responseObserver; private final LinkedBlockingQueue messages = new LinkedBlockingQueue<>(); private final AuthSender sender = new AuthSender(); @@ -84,15 +87,19 @@ public void onNext(HandshakeResponse value) { @Override public byte[] next() { - while (!completed.isDone() || !messages.isEmpty()) { - byte[] bytes = messages.poll(); - if (bytes == null) { - // busy wait. - continue; - } else { - return bytes; - } + final byte[] bytes; + try { + bytes = messages.take(); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + // Fail the request stream, otherwise the server keeps waiting for a message from us. + sender.onError(e); + throw new RuntimeException(e); + } + if (bytes != END_OF_STREAM) { + return bytes; } + messages.add(END_OF_STREAM); if (completed.isCompletedExceptionally()) { // Preserve prior exception behavior @@ -116,13 +123,15 @@ public byte[] next() { @Override public boolean hasNext() { - return !messages.isEmpty(); + final byte[] head = messages.peek(); + return head != null && head != END_OF_STREAM; } }; @Override public void onError(Throwable t) { completed.completeExceptionally(t); + messages.add(END_OF_STREAM); } private class AuthSender implements ClientAuthSender { @@ -149,6 +158,7 @@ public void onError(Throwable cause) { @Override public void onCompleted() { completed.complete(true); + messages.add(END_OF_STREAM); } } } diff --git a/flight/flight-core/src/main/java/org/apache/arrow/flight/auth/ServerAuthWrapper.java b/flight/flight-core/src/main/java/org/apache/arrow/flight/auth/ServerAuthWrapper.java index fba9f9baba..73a560a9dc 100644 --- a/flight/flight-core/src/main/java/org/apache/arrow/flight/auth/ServerAuthWrapper.java +++ b/flight/flight-core/src/main/java/org/apache/arrow/flight/auth/ServerAuthWrapper.java @@ -70,9 +70,11 @@ public static StreamObserver wrapHandshake( private static class AuthObserver implements StreamObserver { + // Queued after the last message so a blocked reader wakes up when the client is done. + private static final byte[] END_OF_STREAM = new byte[0]; + private final StreamObserver responseObserver; private volatile Future future; - private volatile boolean completed = false; private final LinkedBlockingQueue messages = new LinkedBlockingQueue<>(); private final AuthSender sender = new AuthSender(); @@ -92,26 +94,30 @@ public void onNext(HandshakeRequest value) { @Override public byte[] next() { - while (!completed || !messages.isEmpty()) { - byte[] bytes = messages.poll(); - if (bytes == null) { - // busy wait. - continue; - } - return bytes; + final byte[] bytes; + try { + bytes = messages.take(); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new IllegalStateException("Interrupted while waiting for a message.", e); + } + if (bytes == END_OF_STREAM) { + messages.add(END_OF_STREAM); + throw new IllegalStateException("Requesting more messages than client sent."); } - throw new IllegalStateException("Requesting more messages than client sent."); + return bytes; } @Override public boolean hasNext() { - return !messages.isEmpty(); + final byte[] head = messages.peek(); + return head != null && head != END_OF_STREAM; } }; @Override public void onError(Throwable t) { - completed = true; + messages.add(END_OF_STREAM); while (future == null) { /* busy wait */ } @@ -120,7 +126,7 @@ public void onError(Throwable t) { @Override public void onCompleted() { - completed = true; + messages.add(END_OF_STREAM); } private class AuthSender implements ServerAuthSender { diff --git a/flight/flight-core/src/test/java/org/apache/arrow/flight/auth/TestBasicAuth.java b/flight/flight-core/src/test/java/org/apache/arrow/flight/auth/TestBasicAuth.java index 0f202ba2d9..61dd5f8cef 100644 --- a/flight/flight-core/src/test/java/org/apache/arrow/flight/auth/TestBasicAuth.java +++ b/flight/flight-core/src/test/java/org/apache/arrow/flight/auth/TestBasicAuth.java @@ -19,13 +19,23 @@ import static org.apache.arrow.flight.FlightTestUtil.LOCALHOST; import static org.apache.arrow.flight.Location.forGrpcInsecure; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.fail; import com.google.common.collect.ImmutableList; +import io.grpc.ManagedChannel; +import io.grpc.ManagedChannelBuilder; +import io.grpc.stub.StreamObserver; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.util.Arrays; +import java.util.Iterator; +import java.util.Map; import java.util.Optional; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicReference; import org.apache.arrow.flight.Criteria; import org.apache.arrow.flight.FlightClient; import org.apache.arrow.flight.FlightInfo; @@ -35,6 +45,8 @@ import org.apache.arrow.flight.FlightTestUtil; import org.apache.arrow.flight.NoOpFlightProducer; import org.apache.arrow.flight.Ticket; +import org.apache.arrow.flight.impl.Flight.HandshakeResponse; +import org.apache.arrow.flight.impl.FlightServiceGrpc; import org.apache.arrow.memory.BufferAllocator; import org.apache.arrow.memory.RootAllocator; import org.apache.arrow.util.AutoCloseables; @@ -99,6 +111,103 @@ public void didntAuth() { }); } + @Test + public void handshakeBlocksWhileWaitingForClient() throws Exception { + final ManagedChannel channel = + ManagedChannelBuilder.forAddress(LOCALHOST, server.getPort()).usePlaintext().build(); + try { + // Open a handshake but never send a message, so the server waits for the first one. + FlightServiceGrpc.newStub(channel) + .handshake( + new StreamObserver() { + @Override + public void onNext(HandshakeResponse value) {} + + @Override + public void onError(Throwable t) {} + + @Override + public void onCompleted() {} + }); + + final Thread handshakeThread = awaitServerHandshakeThread(); + assertNotNull(handshakeThread, "server handshake did not start"); + Thread.sleep(200); + // The thread must park until a message arrives rather than spin on the queue. + assertEquals(Thread.State.WAITING, handshakeThread.getState()); + } finally { + channel.shutdownNow().awaitTermination(5, TimeUnit.SECONDS); + } + } + + @Test + public void interruptedClientHandshakeEndsServerStream() throws Exception { + final AtomicReference serverThread = new AtomicReference<>(); + try { + assertThrows( + RuntimeException.class, + () -> + client.authenticate( + new ClientAuthHandler() { + @Override + public void authenticate(ClientAuthSender outgoing, Iterator incoming) { + // Let the server park on our first message, then stop mid-handshake. + serverThread.set(awaitServerHandshakeThread()); + Thread.currentThread().interrupt(); + incoming.next(); + } + + @Override + public byte[] getCallToken() { + return VALID_TOKEN; + } + })); + } finally { + // next() re-raises the flag before propagating, so clear it for the rest of the suite. + Thread.interrupted(); + } + assertNotNull(serverThread.get(), "server handshake did not start"); + + // The interrupted client errors the request stream, so the server gives up on the message. + for (int i = 0; i < 100 && isWaitingForHandshakeMessage(serverThread.get()); i++) { + Thread.sleep(50); + } + assertFalse( + isWaitingForHandshakeMessage(serverThread.get()), + "server handshake stayed blocked after the client was interrupted"); + } + + private static Thread awaitServerHandshakeThread() { + for (int i = 0; i < 100; i++) { + for (Map.Entry entry : Thread.getAllStackTraces().entrySet()) { + if (isWaitingForHandshakeMessage(entry.getValue())) { + return entry.getKey(); + } + } + try { + Thread.sleep(50); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + return null; + } + } + return null; + } + + private static boolean isWaitingForHandshakeMessage(Thread thread) { + return isWaitingForHandshakeMessage(thread.getStackTrace()); + } + + private static boolean isWaitingForHandshakeMessage(StackTraceElement[] stack) { + for (StackTraceElement frame : stack) { + if (frame.getClassName().startsWith(ServerAuthWrapper.class.getName()) + && frame.getMethodName().equals("next")) { + return true; + } + } + return false; + } + @BeforeEach public void testSetup() throws IOException { client = FlightClient.builder(allocator, server.getLocation()).build();