Distributed Peer-to-Peer Web Search Engine and Intranet Search Appliance
Java decentralizedintranet-searchintranet-search-enginep2pp2p-networkprivacyprivacy-protectionsearch-enginesearchenginewebweb-search-enginewebsearchwebseearch-engine
Fix error handling for client disconnects
Michael Peter Christen49d3428a4508
diff --git a/build.xml b/build.xmlindex cabc0e5aa..b71301dd8 100644--- a/build.xml+++ b/build.xml@@ -267,9 +267,11 @@<include name="net/yacy/http/Jetty12*Test.java" /><include name="net/yacy/http/servlets/ServletResourceTest.java" /><include name="net/yacy/http/servlets/Jetty12QoSFilterTest.java" />+ <include name="net/yacy/http/servlets/SolrSelectServletTest.java" /><classpath><pathelement location="${build}" /><path refid="compile.path" />+ <fileset dir="${lib}" includes="solr9-bridge-*.jar" /><fileset dir="${libt}" includes="**/*.jar" /></classpath><compilerarg value="-Xlint:deprecation" />@@ -279,10 +281,12 @@<arg value="net.yacy.http.Jetty12ProxyChainTest" /><arg value="net.yacy.http.servlets.ServletResourceTest" /><arg value="net.yacy.http.servlets.Jetty12QoSFilterTest" />+ <arg value="net.yacy.http.servlets.SolrSelectServletTest" /><classpath><pathelement location="${jetty12.test.classes}" /><pathelement location="${build}" /><path refid="compile.path" />+ <fileset dir="${lib}" includes="solr9-bridge-*.jar" /><fileset dir="${libt}" includes="**/*.jar" /></classpath></java>diff --git a/source/net/yacy/http/Jetty12HttpServer.java b/source/net/yacy/http/Jetty12HttpServer.javaindex cc72eab49..b7ad110ec 100644--- a/source/net/yacy/http/Jetty12HttpServer.java+++ b/source/net/yacy/http/Jetty12HttpServer.java@@ -24,9 +24,11 @@ import java.io.IOException;import java.io.Writer;import java.net.InetAddress;import java.net.InetSocketAddress;+import java.nio.channels.ClosedChannelException;import java.nio.file.Files;import java.nio.file.Path;import java.util.EnumSet;+import java.util.Locale;import java.util.concurrent.atomic.AtomicBoolean;import java.util.function.BooleanSupplier;import java.util.function.Supplier;@@ -46,6 +48,7 @@ import org.eclipse.jetty.ee8.webapp.WebAppContext;import org.eclipse.jetty.http.HttpMethod;import org.eclipse.jetty.http.HttpVersion;import org.eclipse.jetty.io.Connection;+import org.eclipse.jetty.io.EofException;import org.eclipse.jetty.security.HashLoginService;import org.eclipse.jetty.security.UserPrincipal;import org.eclipse.jetty.security.UserStore;@@ -405,15 +408,49 @@ public class Jetty12HttpServer implements YaCyHttpServer {if (!completed.compareAndSet(false, true)) {return;}- ConcurrentLog.severe("HTTP", "event=http.request subsystem=http result=exception method="- + request.getMethod() + " target=" + request.getHttpURI().getPath()- + " status=500 reason=" + failure.getMessage());+ final String requestDescription = " method=" + request.getMethod()+ + " target=" + request.getHttpURI().getPath();+ if (isClientDisconnect(failure)) {+ ConcurrentLog.fine("HTTP", "event=http.request subsystem=http result=client_disconnect"+ + requestDescription + " reason=" + failure.getMessage());+ callback.failed(failure);+ return;+ }if (response.isCommitted()) {+ ConcurrentLog.severe("HTTP", "event=http.request subsystem=http result=exception"+ + requestDescription + " status=committed reason=" + failure.getMessage());callback.failed(failure);return;}+ ConcurrentLog.severe("HTTP", "event=http.request subsystem=http result=exception"+ + requestDescription + " status=500 reason=" + failure.getMessage());Response.writeError(request, response, callback, 500, "Internal Server Error");}++ static boolean isClientDisconnect(final Throwable failure) {+ Throwable cause = failure;+ while (cause != null) {+ if (cause instanceof EofException || cause instanceof ClosedChannelException) {+ return true;+ }+ if (cause instanceof IOException && cause.getMessage() != null) {+ final String message = cause.getMessage().toLowerCase(Locale.ROOT);+ if (message.contains("broken pipe") || message.contains("connection reset")+ || message.contains("connection aborted")+ || message.contains("connection closed")+ || message.contains("socket closed")+ || message.contains("closed channel")) {+ return true;+ }+ }+ final Throwable next = cause.getCause();+ if (next == cause) {+ break;+ }+ cause = next;+ }+ return false;+ }}/** Rejects CONNECT explicitly when transparent proxy support is disabled. */diff --git a/source/net/yacy/http/servlets/SolrSelectServlet.java b/source/net/yacy/http/servlets/SolrSelectServlet.javaindex fa4e54d65..4e9898ec4 100644--- a/source/net/yacy/http/servlets/SolrSelectServlet.java+++ b/source/net/yacy/http/servlets/SolrSelectServlet.java@@ -392,11 +392,37 @@ public class SolrSelectServlet extends HttpServlet {}}- private void sendError(HttpServletResponse hresponse, Throwable ex) throws IOException {+ static void sendError(final HttpServletResponse hresponse, final Throwable ex)+ throws IOException, ServletException {+ /*+ * A response writer can fail after Jetty has committed the headers (most+ * commonly when the client disconnects while a result is being streamed).+ * Calling sendError() at that point throws IllegalStateException:+ * COMMITTED and hides the useful original failure from the container.+ */+ if (hresponse.isCommitted()) {+ rethrow(ex);+ }int code = (ex instanceof SolrException) ? ((SolrException) ex).code() : 500;StringWriter sw = new StringWriter();ex.printStackTrace(new PrintWriter(sw));hresponse.sendError((code < 100) ? 500 : code, ex.getMessage() + "\n\n" + sw.toString());}+ private static void rethrow(final Throwable failure) throws IOException, ServletException {+ if (failure instanceof IOException) {+ throw (IOException) failure;+ }+ if (failure instanceof ServletException) {+ throw (ServletException) failure;+ }+ if (failure instanceof RuntimeException) {+ throw (RuntimeException) failure;+ }+ if (failure instanceof Error) {+ throw (Error) failure;+ }+ throw new ServletException(failure);+ }+}diff --git a/test/java/net/yacy/http/Jetty12HttpServerTest.java b/test/java/net/yacy/http/Jetty12HttpServerTest.javaindex f591db7b9..869bbca8e 100644--- a/test/java/net/yacy/http/Jetty12HttpServerTest.java+++ b/test/java/net/yacy/http/Jetty12HttpServerTest.java@@ -8,10 +8,13 @@ import static org.junit.Assert.assertSame;import static org.junit.Assert.assertTrue;import java.io.ByteArrayOutputStream;+import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.lang.reflect.Proxy;import java.net.Socket;+import java.net.SocketException;+import java.nio.channels.ClosedChannelException;import java.nio.charset.StandardCharsets;import java.util.concurrent.atomic.AtomicBoolean;import java.util.concurrent.atomic.AtomicReference;@@ -27,6 +30,7 @@ import javax.servlet.http.HttpServletResponse;import org.eclipse.jetty.ee8.security.authentication.DigestAuthenticator;import org.eclipse.jetty.ee8.servlet.ServletContextHandler;import org.eclipse.jetty.ee8.servlet.ServletHolder;+import org.eclipse.jetty.io.EofException;import org.eclipse.jetty.security.UserIdentity;import org.eclipse.jetty.server.Handler;import org.eclipse.jetty.server.Request;@@ -344,6 +348,26 @@ public class Jetty12HttpServerTest {/** Exception barrier around the complete request pipeline. */public static class CrashProtectionHandlerTest {+ @Test+ public void recognizesClientDisconnectFailuresThroughCauseChain() {+ assertTrue(Jetty12HttpServer.CrashProtectionHandler.isClientDisconnect(+ new IOException("Broken pipe")));+ assertTrue(Jetty12HttpServer.CrashProtectionHandler.isClientDisconnect(+ new SocketException("Connection reset")));+ assertTrue(Jetty12HttpServer.CrashProtectionHandler.isClientDisconnect(+ new IllegalStateException("wrapped", new EofException("closed"))));+ assertTrue(Jetty12HttpServer.CrashProtectionHandler.isClientDisconnect(+ new ClosedChannelException()));+ }++ @Test+ public void doesNotHideUnrelatedIoOrApplicationFailures() {+ assertFalse(Jetty12HttpServer.CrashProtectionHandler.isClientDisconnect(+ new IOException("disk failure")));+ assertFalse(Jetty12HttpServer.CrashProtectionHandler.isClientDisconnect(+ new IllegalStateException("COMMITTED")));+ }+@Testpublic void convertsSynchronousHandlerFailureTo500Response() throws Exception {final Server server = new Server();diff --git a/test/java/net/yacy/http/servlets/SolrSelectServletTest.java b/test/java/net/yacy/http/servlets/SolrSelectServletTest.javanew file mode 100644index 000000000..b88faea47--- /dev/null+++ b/test/java/net/yacy/http/servlets/SolrSelectServletTest.java@@ -0,0 +1,85 @@+package net.yacy.http.servlets;++import static org.junit.Assert.assertEquals;+import static org.junit.Assert.assertFalse;+import static org.junit.Assert.assertSame;+import static org.junit.Assert.assertTrue;+import static org.junit.Assert.fail;++import java.io.IOException;+import java.lang.reflect.Proxy;+import java.util.concurrent.atomic.AtomicBoolean;+import java.util.concurrent.atomic.AtomicInteger;+import java.util.concurrent.atomic.AtomicReference;++import javax.servlet.http.HttpServletResponse;++import org.apache.solr.common.SolrException;+import org.junit.Test;++/** Focused regression tests for {@link SolrSelectServlet}'s error response path. */+public class SolrSelectServletTest {++ @Test+ public void preservesOriginalFailureAfterResponseIsCommitted() throws Exception {+ final AtomicBoolean sendErrorCalled = new AtomicBoolean();+ final HttpServletResponse response = response(true, sendErrorCalled,+ new AtomicInteger(), new AtomicReference<>());+ final IOException original = new IOException("Broken pipe");++ try {+ SolrSelectServlet.sendError(response, original);+ fail("Expected the original write failure");+ } catch (final IOException failure) {+ assertSame(original, failure);+ }+ assertFalse(sendErrorCalled.get());+ }++ @Test+ public void sendsSolrStatusWhenResponseIsNotCommitted() throws Exception {+ final AtomicBoolean sendErrorCalled = new AtomicBoolean();+ final AtomicInteger status = new AtomicInteger();+ final AtomicReference<String> message = new AtomicReference<>();+ final HttpServletResponse response = response(false, sendErrorCalled, status, message);++ SolrSelectServlet.sendError(response,+ new SolrException(SolrException.ErrorCode.BAD_REQUEST, "bad query"));++ assertTrue(sendErrorCalled.get());+ assertEquals(HttpServletResponse.SC_BAD_REQUEST, status.get());+ assertTrue(message.get().contains("bad query"));+ }++ private static HttpServletResponse response(final boolean committed,+ final AtomicBoolean sendErrorCalled, final AtomicInteger status,+ final AtomicReference<String> message) {+ return (HttpServletResponse) Proxy.newProxyInstance(+ SolrSelectServletTest.class.getClassLoader(),+ new Class<?>[] {HttpServletResponse.class},+ (proxy, method, args) -> {+ if ("isCommitted".equals(method.getName())) {+ return committed;+ }+ if ("sendError".equals(method.getName())) {+ sendErrorCalled.set(true);+ status.set((Integer) args[0]);+ if (args.length > 1) {+ message.set((String) args[1]);+ }+ return null;+ }+ final Class<?> returnType = method.getReturnType();+ if (returnType == boolean.class) {+ return false;+ }+ if (returnType == int.class) {+ return 0;+ }+ if (returnType == long.class) {+ return 0L;+ }+ return null;+ });+ }+}