You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@hc.apache.org by ol...@apache.org on 2023/06/13 13:46:44 UTC

[httpcomponents-core] branch master updated (d869b8774 -> 24a84a0e2)

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

olegk pushed a change to branch master
in repository https://gitbox.apache.org/repos/asf/httpcomponents-core.git


    omit d869b8774 HTTPCORE-750: Fixed a defect causing AbstractIOSessionPool to create multiple connections under high load at initialization time due to a race condition
     new 24a84a0e2 HTTPCORE-750: Fixed a defect causing AbstractIOSessionPool to create multiple connections under high load at initialization time due to a race condition

This update added new revisions after undoing existing revisions.
That is to say, some revisions that were in the old version of the
branch are not in the new version.  This situation occurs
when a user --force pushes a change and generates a repository
containing something like this:

 * -- * -- B -- O -- O -- O   (d869b8774)
            \
             N -- N -- N   refs/heads/master (24a84a0e2)

You should already have received notification emails for all of the O
revisions, and so the following emails describe only the N revisions
from the common base, B.

Any revisions marked "omit" are not gone; other references still
refer to them.  Any revisions marked "discard" are gone forever.

The 1 revisions listed above as "new" are entirely new to this
repository and will be described in separate emails.  The revisions
listed as "add" were already present in the repository and have only
been added to this reference.


Summary of changes:
 .../hc/core5/testing/nio/H2ConnPoolTest.java       | 31 +++++++++++++++-------
 1 file changed, 21 insertions(+), 10 deletions(-)


[httpcomponents-core] 01/01: HTTPCORE-750: Fixed a defect causing AbstractIOSessionPool to create multiple connections under high load at initialization time due to a race condition

Posted by ol...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

olegk pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/httpcomponents-core.git

commit 24a84a0e2f708bfe58e12402f9517a820f6163e2
Author: Oleg Kalnichevski <ol...@apache.org>
AuthorDate: Sun Jun 4 10:26:03 2023 +0200

    HTTPCORE-750: Fixed a defect causing AbstractIOSessionPool to create multiple connections under high load at initialization time due to a race condition
---
 .../nio/bootstrap/H2MultiplexingRequester.java     |   5 +
 .../testing/nio/LoggingIOSessionListener.java      |   4 +-
 .../hc/core5/testing/nio/H2ConnPoolTest.java       | 190 +++++++++++++++++++++
 .../hc/core5/reactor/AbstractIOSessionPool.java    |  12 +-
 4 files changed, 208 insertions(+), 3 deletions(-)

diff --git a/httpcore5-h2/src/main/java/org/apache/hc/core5/http2/impl/nio/bootstrap/H2MultiplexingRequester.java b/httpcore5-h2/src/main/java/org/apache/hc/core5/http2/impl/nio/bootstrap/H2MultiplexingRequester.java
index 082ce9e8b..d4edea96e 100644
--- a/httpcore5-h2/src/main/java/org/apache/hc/core5/http2/impl/nio/bootstrap/H2MultiplexingRequester.java
+++ b/httpcore5-h2/src/main/java/org/apache/hc/core5/http2/impl/nio/bootstrap/H2MultiplexingRequester.java
@@ -285,4 +285,9 @@ public class H2MultiplexingRequester extends AsyncRequester{
         return execute(requestProducer, responseConsumer, null, timeout, null, callback);
     }
 
+    @Internal
+    public H2ConnPool getConnPool() {
+        return connPool;
+    }
+
 }
diff --git a/httpcore5-testing/src/main/java/org/apache/hc/core5/testing/nio/LoggingIOSessionListener.java b/httpcore5-testing/src/main/java/org/apache/hc/core5/testing/nio/LoggingIOSessionListener.java
index 509a9aed8..7350884e1 100644
--- a/httpcore5-testing/src/main/java/org/apache/hc/core5/testing/nio/LoggingIOSessionListener.java
+++ b/httpcore5-testing/src/main/java/org/apache/hc/core5/testing/nio/LoggingIOSessionListener.java
@@ -27,6 +27,7 @@
 
 package org.apache.hc.core5.testing.nio;
 
+import org.apache.hc.core5.annotation.Internal;
 import org.apache.hc.core5.http.ConnectionClosedException;
 import org.apache.hc.core5.reactor.IOSession;
 import org.apache.hc.core5.reactor.IOSessionListener;
@@ -39,7 +40,8 @@ public class LoggingIOSessionListener implements IOSessionListener {
 
     private final Logger connLog = LoggerFactory.getLogger("org.apache.hc.core5.http.connection");
 
-    private LoggingIOSessionListener() {
+    @Internal
+    public LoggingIOSessionListener() {
     }
 
     @Override
diff --git a/httpcore5-testing/src/test/java/org/apache/hc/core5/testing/nio/H2ConnPoolTest.java b/httpcore5-testing/src/test/java/org/apache/hc/core5/testing/nio/H2ConnPoolTest.java
new file mode 100644
index 000000000..fc1c15890
--- /dev/null
+++ b/httpcore5-testing/src/test/java/org/apache/hc/core5/testing/nio/H2ConnPoolTest.java
@@ -0,0 +1,190 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation.  For more
+ * information on the Apache Software Foundation, please see
+ * <http://www.apache.org/>.
+ *
+ */
+
+package org.apache.hc.core5.testing.nio;
+
+import java.net.InetSocketAddress;
+import java.util.concurrent.ConcurrentLinkedQueue;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.Future;
+import java.util.concurrent.atomic.AtomicLong;
+
+import org.apache.hc.core5.concurrent.FutureCallback;
+import org.apache.hc.core5.http.HttpHost;
+import org.apache.hc.core5.http.URIScheme;
+import org.apache.hc.core5.http.impl.bootstrap.HttpAsyncServer;
+import org.apache.hc.core5.http2.impl.nio.bootstrap.H2MultiplexingRequester;
+import org.apache.hc.core5.http2.nio.command.PingCommand;
+import org.apache.hc.core5.http2.nio.pool.H2ConnPool;
+import org.apache.hc.core5.http2.nio.support.BasicPingHandler;
+import org.apache.hc.core5.reactor.Command;
+import org.apache.hc.core5.reactor.IOReactorConfig;
+import org.apache.hc.core5.reactor.IOSession;
+import org.apache.hc.core5.reactor.ListenerEndpoint;
+import org.apache.hc.core5.testing.nio.extension.H2AsyncServerResource;
+import org.apache.hc.core5.testing.nio.extension.H2MultiplexingRequesterResource;
+import org.apache.hc.core5.util.Timeout;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.RegisterExtension;
+
+public class H2ConnPoolTest {
+
+    private static final Timeout TIMEOUT = Timeout.ofSeconds(30);
+
+    private final AtomicLong clientConnCount;
+    @RegisterExtension
+    private final H2AsyncServerResource serverResource;
+    @RegisterExtension
+    private final H2MultiplexingRequesterResource clientResource;
+
+    public H2ConnPoolTest() throws Exception {
+        this.serverResource = new H2AsyncServerResource(bootstrap -> bootstrap
+                .setIOReactorConfig(
+                        IOReactorConfig.custom()
+                                .setSoTimeout(TIMEOUT)
+                                .build())
+                .register("*", () -> new EchoHandler(2048))
+        );
+
+        this.clientConnCount = new AtomicLong();
+        this.clientResource = new H2MultiplexingRequesterResource(bootstrap -> bootstrap
+                .setIOReactorConfig(IOReactorConfig.custom()
+                        .setSoTimeout(TIMEOUT)
+                        .build())
+                .setIOSessionListener(new LoggingIOSessionListener() {
+
+                    @Override
+                    public void connected(final IOSession session) {
+                        clientConnCount.incrementAndGet();
+                        super.connected(session);
+                    }
+
+                    @Override
+                    public void disconnected(final IOSession session) {
+                        clientConnCount.decrementAndGet();
+                        super.disconnected(session);
+                    }
+                })
+        );
+    }
+
+    @BeforeEach
+    public void resetCounts() {
+        clientConnCount.set(0);
+    }
+
+    @Test
+    public void testManyGetSession() throws Exception {
+        final int n = 200;
+
+        final HttpAsyncServer server = serverResource.start();
+        final Future<ListenerEndpoint> future = server.listen(new InetSocketAddress(0), URIScheme.HTTP);
+        final ListenerEndpoint listener = future.get();
+        final InetSocketAddress address = (InetSocketAddress) listener.getAddress();
+        final HttpHost target = new HttpHost(URIScheme.HTTP.id, "localhost", address.getPort());
+
+        final H2MultiplexingRequester requester = clientResource.start();
+        final H2ConnPool connPool = requester.getConnPool();
+        final CountDownLatch latch = new CountDownLatch(n);
+        final ConcurrentLinkedQueue<Long> concurrentConnections = new ConcurrentLinkedQueue<>();
+        for (int i = 0; i < n; i++) {
+            connPool.getSession(target, TIMEOUT, new FutureCallback<IOSession>() {
+
+                @Override
+                public void completed(final IOSession session) {
+                    session.enqueue(new PingCommand(new BasicPingHandler(
+                            result -> {
+                                concurrentConnections.add(clientConnCount.get());
+                                latch.countDown();
+                            })), Command.Priority.IMMEDIATE);
+                }
+
+                @Override
+                public void failed(final Exception ex) {
+                    latch.countDown();
+                }
+
+                @Override
+                public void cancelled() {
+                    latch.countDown();
+                }
+
+            });
+        }
+        Assertions.assertTrue(latch.await(TIMEOUT.getDuration(), TIMEOUT.getTimeUnit()));
+
+        requester.initiateShutdown();
+        requester.awaitShutdown(TIMEOUT);
+
+        for (final Long connCount : concurrentConnections) {
+            Assertions.assertEquals(1, (long) connCount);
+        }
+    }
+
+    @Test
+    public void testManyGetSessionFailures() throws Exception {
+        final int n = 200;
+
+        final HttpHost target = new HttpHost(URIScheme.HTTP.id, "pampa.invalid", 8888);
+
+        final H2MultiplexingRequester requester = clientResource.start();
+        final H2ConnPool connPool = requester.getConnPool();
+        final CountDownLatch latch = new CountDownLatch(n);
+        final ConcurrentLinkedQueue<Long> concurrentConnections = new ConcurrentLinkedQueue<>();
+        for (int i = 0; i < n; i++) {
+            connPool.getSession(target, TIMEOUT, new FutureCallback<IOSession>() {
+
+                @Override
+                public void completed(final IOSession session) {
+                    latch.countDown();
+                }
+
+                @Override
+                public void failed(final Exception ex) {
+                    concurrentConnections.add(clientConnCount.get());
+                    latch.countDown();
+                }
+
+                @Override
+                public void cancelled() {
+                    latch.countDown();
+                }
+
+            });
+        }
+
+        requester.initiateShutdown();
+        requester.awaitShutdown(TIMEOUT);
+
+        for (final Long connCount : concurrentConnections) {
+            Assertions.assertEquals(0, (long) connCount);
+        }
+    }
+
+}
diff --git a/httpcore5/src/main/java/org/apache/hc/core5/reactor/AbstractIOSessionPool.java b/httpcore5/src/main/java/org/apache/hc/core5/reactor/AbstractIOSessionPool.java
index efe855d95..339d4ee55 100644
--- a/httpcore5/src/main/java/org/apache/hc/core5/reactor/AbstractIOSessionPool.java
+++ b/httpcore5/src/main/java/org/apache/hc/core5/reactor/AbstractIOSessionPool.java
@@ -182,10 +182,11 @@ public abstract class AbstractIOSessionPool<T> implements ModalCloseable {
                 callback.completed(poolEntry.session);
             } else {
                 poolEntry.requestQueue.add(callback);
-                if (poolEntry.sessionFuture != null && poolEntry.sessionFuture.isDone()) {
+                if (poolEntry.sessionFuture != null && poolEntry.completed) {
                     poolEntry.sessionFuture = null;
                 }
                 if (poolEntry.sessionFuture == null) {
+                    poolEntry.completed = false;
                     poolEntry.sessionFuture = connectSession(
                             namedEndpoint,
                             connectTimeout,
@@ -194,7 +195,12 @@ public abstract class AbstractIOSessionPool<T> implements ModalCloseable {
                                 @Override
                                 public void completed(final IOSession result) {
                                     synchronized (poolEntry) {
-                                        poolEntry.session = result;
+                                        poolEntry.completed = true;
+                                        if (poolEntry.session == null) {
+                                            poolEntry.session = result;
+                                        } else {
+                                            closeSession(result,CloseMode.GRACEFUL);
+                                        }
                                         for (;;) {
                                             final FutureCallback<IOSession> callback = poolEntry.requestQueue.poll();
                                             if (callback != null) {
@@ -209,6 +215,7 @@ public abstract class AbstractIOSessionPool<T> implements ModalCloseable {
                                 @Override
                                 public void failed(final Exception ex) {
                                     synchronized (poolEntry) {
+                                        poolEntry.completed = true;
                                         poolEntry.session = null;
                                         for (;;) {
                                             final FutureCallback<IOSession> callback = poolEntry.requestQueue.poll();
@@ -276,6 +283,7 @@ public abstract class AbstractIOSessionPool<T> implements ModalCloseable {
     static class PoolEntry {
 
         final Queue<FutureCallback<IOSession>> requestQueue;
+        volatile boolean completed;
         volatile Future<IOSession> sessionFuture;
         volatile IOSession session;