This is an automated email from the ASF dual-hosted git repository.

roryqi pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/gravitino.git


The following commit(s) were added to refs/heads/main by this push:
     new f9067d3b22 [#13912] fix(server): Let in-flight requests finish when 
the web server stops (#13913)
f9067d3b22 is described below

commit f9067d3b22729e6baad79a9a43103ab42fa121c4
Author: YangJie <[email protected]>
AuthorDate: Thu Nov 12 06:04:46 2026 -0500

    [#13912] fix(server): Let in-flight requests finish when the web server 
stops (#13913)
    
    ### What changes were proposed in this pull request?
    
    - `JettyServer` wraps its handlers in a Jetty `StatisticsHandler`. When
    the server stops, Jetty now waits up to `stopTimeout` for in-flight
    requests before it closes their connections. New connections are refused
    during that wait, and requests that arrive on a kept-alive connection
    get 503. This covers the Gravitino server, the Iceberg REST server and
    the Lance REST server.
    - `GravitinoServer.stop()` closes the authorizer after the web server
    has stopped instead of before, so requests that are still being drained
    can complete their authorization checks.
    
    ### Why are the changes needed?
    
    Without a graceful handler, stopping the server closed the connections
    of in-flight requests at once, while the requests themselves kept
    running. Clients lost the result of operations that completed, for
    example a create that a retry then rejects with 409. On the Gravitino
    server, the shutdown hook also closed the authorizer 3 seconds after
    SIGTERM, before the web server had stopped.
    
    Fix: #13912
    
    ### Does this PR introduce _any_ user-facing change?
    
    Stopping a server now waits up to `stopTimeout` (30 s by default) for
    in-flight requests to finish; requests still running after that are cut
    off as before. `bin/<server>.sh stop` still sends `kill -9` after about
    10 seconds and `docker stop` waits 10 seconds by default, so on those
    paths the wait is bounded by that.
    
    ### How was this patch tested?
    
    - `TestJettyServer.testStopLetsInFlightRequestFinish`: stops the server
    while a servlet is blocked, waits until new connections are refused,
    checks the request is still pending, then releases the servlet and
    expects the client to get its response.
    - `TestGravitinoServer.testStopKeepsAuthorizerUntilWebServerStops`: the
    authorizer is still set while the web server stops.
    - Manual check with a locally built Iceberg REST server and a REST
    backend whose create takes 8 s, stopped with SIGTERM 2 s into the
    request: before, the client got an empty reply at once; after, it got
    200 when the backend finished, about 6 s later. The JVM exited at about
    the same time in both cases.
    
    ---------
    
    Co-authored-by: roryqi <[email protected]>
---
 .../apache/gravitino/server/web/JettyServer.java   |  7 +-
 .../gravitino/server/web/TestJettyServer.java      | 76 ++++++++++++++++++++++
 .../apache/gravitino/server/GravitinoServer.java   |  3 +-
 .../gravitino/server/TestGravitinoServer.java      | 26 ++++++++
 4 files changed, 110 insertions(+), 2 deletions(-)

diff --git 
a/server-common/src/main/java/org/apache/gravitino/server/web/JettyServer.java 
b/server-common/src/main/java/org/apache/gravitino/server/web/JettyServer.java
index ee53532a39..63e20a09bd 100644
--- 
a/server-common/src/main/java/org/apache/gravitino/server/web/JettyServer.java
+++ 
b/server-common/src/main/java/org/apache/gravitino/server/web/JettyServer.java
@@ -50,6 +50,7 @@ import org.eclipse.jetty.server.ServerConnector;
 import org.eclipse.jetty.server.SslConnectionFactory;
 import org.eclipse.jetty.server.handler.ErrorHandler;
 import org.eclipse.jetty.server.handler.HandlerCollection;
+import org.eclipse.jetty.server.handler.StatisticsHandler;
 import org.eclipse.jetty.servlet.DefaultServlet;
 import org.eclipse.jetty.servlet.FilterHolder;
 import org.eclipse.jetty.servlet.ServletContextHandler;
@@ -183,7 +184,11 @@ public class JettyServer {
 
     HandlerCollection handlers = new HandlerCollection();
     handlers.addHandler(servletContextHandler);
-    server.setHandler(handlers);
+    // Without a StatisticsHandler, stopping the server closes the connections 
of in-flight
+    // requests at once. With it, stop waits up to the stop timeout for them 
to finish.
+    StatisticsHandler statisticsHandler = new StatisticsHandler();
+    statisticsHandler.setHandler(handlers);
+    server.setHandler(statisticsHandler);
   }
 
   public synchronized void start() throws RuntimeException {
diff --git 
a/server-common/src/test/java/org/apache/gravitino/server/web/TestJettyServer.java
 
b/server-common/src/test/java/org/apache/gravitino/server/web/TestJettyServer.java
index b48b527f3d..5c3500aa63 100644
--- 
a/server-common/src/test/java/org/apache/gravitino/server/web/TestJettyServer.java
+++ 
b/server-common/src/test/java/org/apache/gravitino/server/web/TestJettyServer.java
@@ -23,6 +23,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals;
 import static org.junit.jupiter.api.Assertions.assertFalse;
 import static org.junit.jupiter.api.Assertions.assertThrows;
 import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
 import static org.junit.jupiter.api.Assumptions.assumeTrue;
 import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.mockStatic;
@@ -37,6 +38,9 @@ import java.net.Socket;
 import java.net.URL;
 import java.nio.charset.StandardCharsets;
 import java.util.Arrays;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
 import javax.servlet.Filter;
 import javax.servlet.Servlet;
 import javax.servlet.http.HttpServlet;
@@ -179,6 +183,59 @@ public class TestJettyServer {
     }
   }
 
+  @Test
+  public void testStopLetsInFlightRequestFinish() throws Exception {
+    int port = RESTUtils.findAvailablePort(5000, 6000);
+    Config config = new Config(false) {};
+    config.set(JettyServerConfig.WEBSERVER_HOST, "127.0.0.1");
+    config.set(JettyServerConfig.WEBSERVER_HTTP_PORT, port);
+    jettyServer.initialize(JettyServerConfig.fromConfig(config), "test", 
false);
+    SlowServlet servlet = new SlowServlet();
+    jettyServer.addServlet(servlet, "/slow");
+    jettyServer.start();
+
+    CompletableFuture<String> response =
+        CompletableFuture.supplyAsync(
+            () -> {
+              try {
+                HttpURLConnection connection =
+                    (HttpURLConnection)
+                        new URL("http://127.0.0.1:"; + port + 
"/slow").openConnection();
+                try (Reader body =
+                    new InputStreamReader(connection.getInputStream(), 
StandardCharsets.UTF_8)) {
+                  return connection.getResponseCode() + " " + 
CharStreams.toString(body);
+                } finally {
+                  connection.disconnect();
+                }
+              } catch (IOException e) {
+                return e.toString();
+              }
+            });
+    assertTrue(servlet.entered.await(10, TimeUnit.SECONDS));
+
+    // Stop while the request is still being handled. Once new connections are 
refused the stop
+    // has started, and the request must still be waiting for the servlet.
+    CompletableFuture<Void> stop = 
CompletableFuture.runAsync(jettyServer::stop);
+    waitUntilConnectionsRefused(port);
+    assertFalse(response.isDone(), response::join);
+    servlet.release.countDown();
+
+    assertEquals("200 done", response.get(10, TimeUnit.SECONDS));
+    stop.get(10, TimeUnit.SECONDS);
+  }
+
+  private static void waitUntilConnectionsRefused(int port) throws 
InterruptedException {
+    long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(10);
+    while (System.nanoTime() < deadline) {
+      try (Socket ignored = new Socket("127.0.0.1", port)) {
+        Thread.sleep(50);
+      } catch (IOException e) {
+        return;
+      }
+    }
+    fail("The server still accepts connections after stop was called");
+  }
+
   /**
    * Sends real requests over IPv4 and IPv6 loopback, so the peer address 
comes from Jetty itself
    * (which brackets IPv6 peers) rather than from a mock.
@@ -271,6 +328,25 @@ public class TestJettyServer {
     }
   }
 
+  private static class SlowServlet extends HttpServlet {
+    private final CountDownLatch entered = new CountDownLatch(1);
+    private final CountDownLatch release = new CountDownLatch(1);
+
+    @Override
+    protected void doGet(HttpServletRequest request, HttpServletResponse 
response)
+        throws IOException {
+      entered.countDown();
+      try {
+        release.await(10, TimeUnit.SECONDS);
+      } catch (InterruptedException e) {
+        Thread.currentThread().interrupt();
+      }
+      // A fixed length lets Jetty finish the response before it signals the 
drain.
+      response.setContentLength("done".length());
+      response.getWriter().write("done");
+    }
+  }
+
   private int startServer() throws IOException {
     int port = RESTUtils.findAvailablePort(5000, 6000);
     Config config = new Config(false) {};
diff --git 
a/server/src/main/java/org/apache/gravitino/server/GravitinoServer.java 
b/server/src/main/java/org/apache/gravitino/server/GravitinoServer.java
index 628a8573a5..7926a10b10 100644
--- a/server/src/main/java/org/apache/gravitino/server/GravitinoServer.java
+++ b/server/src/main/java/org/apache/gravitino/server/GravitinoServer.java
@@ -290,8 +290,9 @@ public class GravitinoServer extends ResourceConfig {
   }
 
   public void stop() throws IOException {
-    GravitinoAuthorizerProvider.getInstance().close();
+    // Stop the web server first: it waits for in-flight requests, which still 
need the authorizer.
     server.stop();
+    GravitinoAuthorizerProvider.getInstance().close();
     gravitinoEnv.shutdown();
     if (lineageService != null) {
       lineageService.close();
diff --git 
a/server/src/test/java/org/apache/gravitino/server/TestGravitinoServer.java 
b/server/src/test/java/org/apache/gravitino/server/TestGravitinoServer.java
index 7aa46fa6e4..3828726810 100644
--- a/server/src/test/java/org/apache/gravitino/server/TestGravitinoServer.java
+++ b/server/src/test/java/org/apache/gravitino/server/TestGravitinoServer.java
@@ -21,6 +21,7 @@ package org.apache.gravitino.server;
 import static org.apache.gravitino.Configs.ENTITY_RELATIONAL_JDBC_BACKEND_PATH;
 import static org.junit.jupiter.api.Assertions.assertEquals;
 import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertSame;
 import static org.junit.jupiter.api.Assertions.assertThrows;
 import static org.junit.jupiter.api.Assertions.assertTrue;
 
@@ -42,8 +43,10 @@ import java.util.List;
 import java.util.Map;
 import java.util.Set;
 import java.util.UUID;
+import java.util.concurrent.atomic.AtomicReference;
 import org.apache.commons.io.FileUtils;
 import org.apache.gravitino.GravitinoEnv;
+import org.apache.gravitino.authorization.GravitinoAuthorizer;
 import org.apache.gravitino.auxiliary.AuxiliaryServiceManager;
 import org.apache.gravitino.rest.RESTUtils;
 import org.apache.gravitino.secret.SecretProviderRegistry;
@@ -185,6 +188,29 @@ public class TestGravitinoServer {
     gravitinoServer.stop();
   }
 
+  @Test
+  public void testStopKeepsAuthorizerUntilWebServerStops() throws Exception {
+    GravitinoAuthorizer authorizer = Mockito.mock(GravitinoAuthorizer.class);
+    JettyServer webServer = Mockito.mock(JettyServer.class);
+    AtomicReference<GravitinoAuthorizer> authorizerDuringStop = new 
AtomicReference<>();
+    Mockito.doAnswer(
+            invocation -> {
+              
authorizerDuringStop.set(GravitinoEnv.getInstance().gravitinoAuthorizer());
+              return null;
+            })
+        .when(webServer)
+        .stop();
+    Field serverField = GravitinoServer.class.getDeclaredField("server");
+    serverField.setAccessible(true);
+    serverField.set(gravitinoServer, webServer);
+    GravitinoEnv.getInstance().setGravitinoAuthorizer(authorizer);
+
+    gravitinoServer.stop();
+
+    // Requests that the web server drains while stopping still need the 
authorizer.
+    assertSame(authorizer, authorizerDuringStop.get());
+  }
+
   @Test
   public void testInitializeWithLoadFromFileException() throws Exception {
     ServerConfig config = new ServerConfig();

Reply via email to