You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@pulsar.apache.org by lh...@apache.org on 2024/10/04 11:28:31 UTC

(pulsar) branch branch-3.3 updated (d4aa14de755 -> 43aabfc7209)

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

lhotari pushed a change to branch branch-3.3
in repository https://gitbox.apache.org/repos/asf/pulsar.git


    from d4aa14de755 [fix][sec] Upgrade Avro to 1.11.4 to address CVE-2024-47561 (#23394)
     new 63ca5ecb9e1 [fix] [log] Do not print error log if tenant/namespace does not exist when calling get topic metadata (#23291)
     new 25feaf791ed [fix][broker] Fix the broker registery cannot recover from the metadata node deletion (#23359)
     new 57304ed1706 [fix][misc] Log Conscrypt security provider initialization warnings at debug level (#23364)
     new bc578e07cad [improve] Install openssl in the docker image to fix compatibility with Apache Pulsar Helm chart (#23362)
     new 8b47a528ded [improve][build] Use amazoncorretto:21-alpine image instead of apk installation (#22973)
     new d0ab26e3bef [improve][ci] Switch to Java 21 as default JVM version for CI (#23373)
     new caf214e70ec [improve] Upgrade Pulsar Python client in docker image to 3.5.0 (#23377)
     new 0c6abe0f323 [fix][broker] Cancel possible pending replay read in cancelPendingRead (#23384)
     new 43aabfc7209 [fix][broker] Fix out-of-order issues with ConsistentHashingStickyKeyConsumerSelector (#23327)

The 9 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:
 .github/workflows/pulsar-ci.yaml                   |  14 +-
 bin/function-localrunner                           |   9 +-
 conf/bkenv.sh                                      |  14 +-
 conf/pulsar_env.sh                                 |  13 +-
 docker/pulsar/Dockerfile                           |  10 +-
 docker/pulsar/pom.xml                              |   1 +
 pom.xml                                            |  30 +-
 .../loadbalance/extensions/BrokerRegistry.java     |   6 +-
 .../loadbalance/extensions/BrokerRegistryImpl.java |  57 ++--
 ...ConsistentHashingStickyKeyConsumerSelector.java | 104 +++---
 .../broker/service/ConsumerIdentityWrapper.java    |  70 ++++
 .../broker/service/ConsumerNameIndexTracker.java   | 136 ++++++++
 .../apache/pulsar/broker/service/ServerCnx.java    |  41 ++-
 .../PersistentDispatcherMultipleConsumers.java     |   3 +-
 .../broker/admin/GetPartitionMetadataTest.java     |  51 +++
 .../extensions/BrokerRegistryIntegrationTest.java  | 124 +++++++
 .../loadbalance/extensions/BrokerRegistryTest.java |   6 +-
 .../extensions/ExtensibleLoadManagerImplTest.java  |   2 +-
 ...istentHashingStickyKeyConsumerSelectorTest.java | 366 ++++++++++++++++++++-
 .../service/ConsumerIdentityWrapperTest.java       |  68 ++++
 .../service/ConsumerNameIndexTrackerTest.java      | 157 +++++++++
 ...ntStickyKeyDispatcherMultipleConsumersTest.java |   9 +-
 .../java/org/apache/pulsar/client/api/Range.java   |  11 +-
 .../apache/pulsar/common/util/SecurityUtility.java |   8 +-
 24 files changed, 1155 insertions(+), 155 deletions(-)
 create mode 100644 pulsar-broker/src/main/java/org/apache/pulsar/broker/service/ConsumerIdentityWrapper.java
 create mode 100644 pulsar-broker/src/main/java/org/apache/pulsar/broker/service/ConsumerNameIndexTracker.java
 create mode 100644 pulsar-broker/src/test/java/org/apache/pulsar/broker/loadbalance/extensions/BrokerRegistryIntegrationTest.java
 create mode 100644 pulsar-broker/src/test/java/org/apache/pulsar/broker/service/ConsumerIdentityWrapperTest.java
 create mode 100644 pulsar-broker/src/test/java/org/apache/pulsar/broker/service/ConsumerNameIndexTrackerTest.java


(pulsar) 06/09: [improve][ci] Switch to Java 21 as default JVM version for CI (#23373)

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

lhotari pushed a commit to branch branch-3.3
in repository https://gitbox.apache.org/repos/asf/pulsar.git

commit d0ab26e3bef0b22f4e741def7d67815268c32418
Author: Lari Hotari <lh...@users.noreply.github.com>
AuthorDate: Mon Sep 30 07:09:04 2024 +0300

    [improve][ci] Switch to Java 21 as default JVM version for CI (#23373)
    
    (cherry picked from commit b24285029b1113840ded42404229bc0eb344d5bd)
---
 .github/workflows/pulsar-ci.yaml | 14 +++++++-------
 bin/function-localrunner         |  9 ++++++++-
 conf/bkenv.sh                    | 14 +++++++++++---
 conf/pulsar_env.sh               | 13 ++++++++++---
 docker/pulsar/Dockerfile         |  3 ++-
 docker/pulsar/pom.xml            |  1 +
 pom.xml                          | 28 +---------------------------
 7 files changed, 40 insertions(+), 42 deletions(-)

diff --git a/.github/workflows/pulsar-ci.yaml b/.github/workflows/pulsar-ci.yaml
index dd93003eecc..ad017674ac6 100644
--- a/.github/workflows/pulsar-ci.yaml
+++ b/.github/workflows/pulsar-ci.yaml
@@ -25,9 +25,9 @@ on:
       - branch-*
       - pulsar-*
   schedule:
-    # scheduled job with JDK 17
-    - cron: '0 12 * * *'
     # scheduled job with JDK 21
+    - cron: '0 12 * * *'
+    # scheduled job with JDK 17
     # if cron expression is changed, make sure to update the expression in jdk_major_version step in preconditions job
     - cron: '0 6 * * *'
   workflow_dispatch:
@@ -44,7 +44,7 @@ on:
         options:
           - '17'
           - '21'
-        default: '17'
+        default: '21'
       trace_test_resource_cleanup:
         description: 'Collect thread & heap information before exiting a test JVM. When set to "on", thread dump and heap histogram will be collected. When set to "full", a heap dump will also be collected.'
         required: true
@@ -95,13 +95,13 @@ jobs:
       - name: Select JDK major version
         id: jdk_major_version
         run: |
-          # use JDK 21 for the scheduled build with cron expression '0 6 * * *'
+          # use JDK 17 for the scheduled build with cron expression '0 6 * * *'
           if [[ "${{ github.event_name == 'schedule' && github.event.schedule == '0 6 * * *' && 'true' || 'false' }}" == "true" ]]; then
-            echo "jdk_major_version=21" >> $GITHUB_OUTPUT
+            echo "jdk_major_version=17" >> $GITHUB_OUTPUT
             exit 0
           fi
-          # use JDK 17 for build unless overridden with workflow_dispatch input
-          echo "jdk_major_version=${{ github.event_name == 'workflow_dispatch' && github.event.inputs.jdk_major_version || '17'}}" >> $GITHUB_OUTPUT
+          # use JDK 21 for build unless overridden with workflow_dispatch input
+          echo "jdk_major_version=${{ github.event_name == 'workflow_dispatch' && github.event.inputs.jdk_major_version || '21'}}" >> $GITHUB_OUTPUT
 
       - name: checkout
         if: ${{ github.event_name == 'pull_request' }}
diff --git a/bin/function-localrunner b/bin/function-localrunner
index 2e0aa0f6dff..84de2803794 100755
--- a/bin/function-localrunner
+++ b/bin/function-localrunner
@@ -37,7 +37,14 @@ fi
 PULSAR_MEM=${PULSAR_MEM:-"-Xmx128m -XX:MaxDirectMemorySize=128m"}
 
 # Garbage collection options
-PULSAR_GC=${PULSAR_GC:-"-XX:+UseZGC -XX:+PerfDisableSharedMem -XX:+AlwaysPreTouch"}
+if [ -z "$PULSAR_GC" ]; then
+  PULSAR_GC="-XX:+PerfDisableSharedMem -XX:+AlwaysPreTouch"
+  if [[ $JAVA_MAJOR_VERSION -ge 21 ]]; then
+    PULSAR_GC="-XX:+UseZGC -XX:+ZGenerational ${PULSAR_GC}"
+  else
+    PULSAR_GC="-XX:+UseZGC ${PULSAR_GC}"
+  fi
+fi
 
 # Garbage collection log.
 IS_JAVA_8=$( $JAVA -version 2>&1 | grep version | grep '"1\.8' )
diff --git a/conf/bkenv.sh b/conf/bkenv.sh
index b41532d3a0c..8beea47cee3 100644
--- a/conf/bkenv.sh
+++ b/conf/bkenv.sh
@@ -37,9 +37,6 @@ BOOKIE_LOG_DIR=${BOOKIE_LOG_DIR:-"${PULSAR_LOG_DIR}"}
 # Memory size options
 BOOKIE_MEM=${BOOKIE_MEM:-${PULSAR_MEM:-"-Xms2g -Xmx2g -XX:MaxDirectMemorySize=2g"}}
 
-# Garbage collection options
-BOOKIE_GC=${BOOKIE_GC:-${PULSAR_GC:-"-XX:+UseZGC -XX:+PerfDisableSharedMem -XX:+AlwaysPreTouch"}}
-
 if [ -z "$JAVA_HOME" ]; then
   JAVA_BIN=java
 else
@@ -60,6 +57,17 @@ for token in $("$JAVA_BIN" -version 2>&1 | grep 'version "'); do
     fi
 done
 
+# Garbage collection options
+BOOKIE_GC="${BOOKIE_GC:-${PULSAR_GC}}"
+if [ -z "$BOOKIE_GC" ]; then
+  BOOKIE_GC="-XX:+PerfDisableSharedMem -XX:+AlwaysPreTouch"
+  if [[ $JAVA_MAJOR_VERSION -ge 21 ]]; then
+    BOOKIE_GC="-XX:+UseZGC -XX:+ZGenerational ${BOOKIE_GC}"
+  else
+    BOOKIE_GC="-XX:+UseZGC ${BOOKIE_GC}"
+  fi
+fi
+
 if [[ -z "$BOOKIE_GC_LOG" ]]; then
   # fallback to PULSAR_GC_LOG if it is set
   BOOKIE_GC_LOG="$PULSAR_GC_LOG"
diff --git a/conf/pulsar_env.sh b/conf/pulsar_env.sh
index 3a069e31fdc..f95d0ac83c1 100755
--- a/conf/pulsar_env.sh
+++ b/conf/pulsar_env.sh
@@ -44,9 +44,6 @@
 # Extra options to be passed to the jvm
 PULSAR_MEM=${PULSAR_MEM:-"-Xms2g -Xmx2g -XX:MaxDirectMemorySize=4g"}
 
-# Garbage collection options
-PULSAR_GC=${PULSAR_GC:-"-XX:+UseZGC -XX:+PerfDisableSharedMem -XX:+AlwaysPreTouch"}
-
 if [ -z "$JAVA_HOME" ]; then
   JAVA_BIN=java
 else
@@ -67,6 +64,16 @@ for token in $("$JAVA_BIN" -version 2>&1 | grep 'version "'); do
     fi
 done
 
+# Garbage collection options
+if [ -z "$PULSAR_GC" ]; then
+  PULSAR_GC="-XX:+PerfDisableSharedMem -XX:+AlwaysPreTouch"
+  if [[ $JAVA_MAJOR_VERSION -ge 21 ]]; then
+    PULSAR_GC="-XX:+UseZGC -XX:+ZGenerational ${PULSAR_GC}"
+  else
+    PULSAR_GC="-XX:+UseZGC ${PULSAR_GC}"
+  fi
+fi
+
 PULSAR_GC_LOG_DIR=${PULSAR_GC_LOG_DIR:-"${PULSAR_LOG_DIR}"}
 
 if [[ -z "$PULSAR_GC_LOG" ]]; then
diff --git a/docker/pulsar/Dockerfile b/docker/pulsar/Dockerfile
index 38b74e8503d..f3b0f3d944b 100644
--- a/docker/pulsar/Dockerfile
+++ b/docker/pulsar/Dockerfile
@@ -18,6 +18,7 @@
 #
 
 ARG ALPINE_VERSION=3.20
+ARG IMAGE_JDK_MAJOR_VERSION=21
 
 # First create a stage with just the Pulsar tarball and scripts
 FROM alpine:$ALPINE_VERSION as pulsar
@@ -54,7 +55,7 @@ RUN chmod -R o+rx /pulsar
 RUN echo 'OPTS="$OPTS -Dorg.xerial.snappy.use.systemlib=true"' >> /pulsar/conf/bkenv.sh
 
 ###  Create one stage to include JVM distribution
-FROM amazoncorretto:21-alpine AS jvm
+FROM amazoncorretto:${IMAGE_JDK_MAJOR_VERSION}-alpine AS jvm
 
 RUN apk add --no-cache binutils
 
diff --git a/docker/pulsar/pom.xml b/docker/pulsar/pom.xml
index a533ba9d36d..eaf1ed9c727 100644
--- a/docker/pulsar/pom.xml
+++ b/docker/pulsar/pom.xml
@@ -83,6 +83,7 @@
                           <PULSAR_TARBALL>target/pulsar-server-distribution-${project.version}-bin.tar.gz</PULSAR_TARBALL>
                           <PULSAR_CLIENT_PYTHON_VERSION>${pulsar.client.python.version}</PULSAR_CLIENT_PYTHON_VERSION>
                           <SNAPPY_VERSION>${snappy.version}</SNAPPY_VERSION>
+                          <IMAGE_JDK_MAJOR_VERSION>${IMAGE_JDK_MAJOR_VERSION}</IMAGE_JDK_MAJOR_VERSION>
                         </args>
                         <contextDir>${project.basedir}</contextDir>
                         <tags>
diff --git a/pom.xml b/pom.xml
index 61383675bbe..00cd76e9916 100644
--- a/pom.xml
+++ b/pom.xml
@@ -84,9 +84,7 @@ flexible messaging model and an intuitive client API.</description>
 
     <pulsar.client.python.version>3.4.0</pulsar.client.python.version>
 
-    <UBUNTU_MIRROR>http://archive.ubuntu.com/ubuntu/</UBUNTU_MIRROR>
-    <UBUNTU_SECURITY_MIRROR>http://security.ubuntu.com/ubuntu/</UBUNTU_SECURITY_MIRROR>
-    <IMAGE_JDK_MAJOR_VERSION>17</IMAGE_JDK_MAJOR_VERSION>
+    <IMAGE_JDK_MAJOR_VERSION>21</IMAGE_JDK_MAJOR_VERSION>
 
     <!--config keys to configure test selection -->
     <include>**/Test*.java,**/*Test.java,**/*Tests.java,**/*TestCase.java</include>
@@ -2738,30 +2736,6 @@ flexible messaging model and an intuitive client API.</description>
       </properties>
     </profile>
 
-    <profile>
-      <id>ubuntu-mirror-set</id>
-      <activation>
-        <property>
-          <name>env.UBUNTU_MIRROR</name>
-        </property>
-      </activation>
-      <properties>
-        <!-- Override the default value with the environment variable -->
-        <UBUNTU_MIRROR>${env.UBUNTU_MIRROR}</UBUNTU_MIRROR>
-      </properties>
-    </profile>
-    <profile>
-      <id>ubuntu-security-mirror-set</id>
-      <activation>
-        <property>
-          <name>env.UBUNTU_SECURITY_MIRROR</name>
-        </property>
-      </activation>
-      <properties>
-        <!-- Override the default value with the environment variable -->
-        <UBUNTU_SECURITY_MIRROR>${env.UBUNTU_SECURITY_MIRROR}</UBUNTU_SECURITY_MIRROR>
-      </properties>
-    </profile>
     <profile>
       <id>jdk-major-version-set</id>
       <activation>


(pulsar) 08/09: [fix][broker] Cancel possible pending replay read in cancelPendingRead (#23384)

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

lhotari pushed a commit to branch branch-3.3
in repository https://gitbox.apache.org/repos/asf/pulsar.git

commit 0c6abe0f3233a8ca68d26e53c01ebe5f7b2931e2
Author: Lari Hotari <lh...@users.noreply.github.com>
AuthorDate: Tue Oct 1 22:54:32 2024 +0300

    [fix][broker] Cancel possible pending replay read in cancelPendingRead (#23384)
    
    (cherry picked from commit d2c91b1e1a8fc2fb233eb2856ddb6f53511ba201)
---
 .../service/persistent/PersistentDispatcherMultipleConsumers.java      | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)

diff --git a/pulsar-broker/src/main/java/org/apache/pulsar/broker/service/persistent/PersistentDispatcherMultipleConsumers.java b/pulsar-broker/src/main/java/org/apache/pulsar/broker/service/persistent/PersistentDispatcherMultipleConsumers.java
index 2983639c76a..07178cd9612 100644
--- a/pulsar-broker/src/main/java/org/apache/pulsar/broker/service/persistent/PersistentDispatcherMultipleConsumers.java
+++ b/pulsar-broker/src/main/java/org/apache/pulsar/broker/service/persistent/PersistentDispatcherMultipleConsumers.java
@@ -600,8 +600,9 @@ public class PersistentDispatcherMultipleConsumers extends AbstractDispatcherMul
 
     @Override
     protected void cancelPendingRead() {
-        if (havePendingRead && cursor.cancelPendingReadRequest()) {
+        if ((havePendingRead || havePendingReplayRead) && cursor.cancelPendingReadRequest()) {
             havePendingRead = false;
+            havePendingReplayRead = false;
         }
     }
 


(pulsar) 07/09: [improve] Upgrade Pulsar Python client in docker image to 3.5.0 (#23377)

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

lhotari pushed a commit to branch branch-3.3
in repository https://gitbox.apache.org/repos/asf/pulsar.git

commit caf214e70ec78c632f2c1ebeae30ff52f7a258ee
Author: Lari Hotari <lh...@users.noreply.github.com>
AuthorDate: Mon Sep 30 17:10:15 2024 +0300

    [improve] Upgrade Pulsar Python client in docker image to 3.5.0 (#23377)
    
    (cherry picked from commit 9980967d777040706f15cc4a976af81d85c7faa6)
---
 pom.xml | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/pom.xml b/pom.xml
index 00cd76e9916..b6a3b2134c2 100644
--- a/pom.xml
+++ b/pom.xml
@@ -82,7 +82,7 @@ flexible messaging model and an intuitive client API.</description>
     <pulsar.broker.compiler.release>${maven.compiler.target}</pulsar.broker.compiler.release>
     <pulsar.client.compiler.release>8</pulsar.client.compiler.release>
 
-    <pulsar.client.python.version>3.4.0</pulsar.client.python.version>
+    <pulsar.client.python.version>3.5.0</pulsar.client.python.version>
 
     <IMAGE_JDK_MAJOR_VERSION>21</IMAGE_JDK_MAJOR_VERSION>
 


(pulsar) 02/09: [fix][broker] Fix the broker registery cannot recover from the metadata node deletion (#23359)

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

lhotari pushed a commit to branch branch-3.3
in repository https://gitbox.apache.org/repos/asf/pulsar.git

commit 25feaf791ed69405ea7aa075b63d2fa42ca7ec72
Author: Yunze Xu <xy...@163.com>
AuthorDate: Fri Sep 27 19:49:02 2024 +0800

    [fix][broker] Fix the broker registery cannot recover from the metadata node deletion (#23359)
    
    (cherry picked from commit 95bd1d1dd3d447f0705a96092afbc9d6bd6cd1dc)
---
 .../loadbalance/extensions/BrokerRegistry.java     |   6 +-
 .../loadbalance/extensions/BrokerRegistryImpl.java |  57 ++++++----
 .../extensions/BrokerRegistryIntegrationTest.java  | 124 +++++++++++++++++++++
 .../loadbalance/extensions/BrokerRegistryTest.java |   6 +-
 .../extensions/ExtensibleLoadManagerImplTest.java  |   2 +-
 5 files changed, 167 insertions(+), 28 deletions(-)

diff --git a/pulsar-broker/src/main/java/org/apache/pulsar/broker/loadbalance/extensions/BrokerRegistry.java b/pulsar-broker/src/main/java/org/apache/pulsar/broker/loadbalance/extensions/BrokerRegistry.java
index 8133d4c4827..79dba9c6334 100644
--- a/pulsar-broker/src/main/java/org/apache/pulsar/broker/loadbalance/extensions/BrokerRegistry.java
+++ b/pulsar-broker/src/main/java/org/apache/pulsar/broker/loadbalance/extensions/BrokerRegistry.java
@@ -25,6 +25,8 @@ import java.util.concurrent.CompletableFuture;
 import java.util.function.BiConsumer;
 import org.apache.pulsar.broker.PulsarServerException;
 import org.apache.pulsar.broker.loadbalance.extensions.data.BrokerLookupData;
+import org.apache.pulsar.common.classification.InterfaceAudience;
+import org.apache.pulsar.common.classification.InterfaceStability;
 import org.apache.pulsar.metadata.api.MetadataStoreException;
 import org.apache.pulsar.metadata.api.NotificationType;
 
@@ -32,6 +34,8 @@ import org.apache.pulsar.metadata.api.NotificationType;
  * Responsible for registering the current Broker lookup info to
  * the distributed store (e.g. Zookeeper) for broker discovery.
  */
+@InterfaceAudience.LimitedPrivate
+@InterfaceStability.Unstable
 public interface BrokerRegistry extends AutoCloseable {
 
     /**
@@ -47,7 +51,7 @@ public interface BrokerRegistry extends AutoCloseable {
     /**
      * Register local broker to metadata store.
      */
-    void register() throws MetadataStoreException;
+    CompletableFuture<Void> registerAsync();
 
     /**
      * Unregister the broker.
diff --git a/pulsar-broker/src/main/java/org/apache/pulsar/broker/loadbalance/extensions/BrokerRegistryImpl.java b/pulsar-broker/src/main/java/org/apache/pulsar/broker/loadbalance/extensions/BrokerRegistryImpl.java
index 44f6287b2e1..296d9a77fd7 100644
--- a/pulsar-broker/src/main/java/org/apache/pulsar/broker/loadbalance/extensions/BrokerRegistryImpl.java
+++ b/pulsar-broker/src/main/java/org/apache/pulsar/broker/loadbalance/extensions/BrokerRegistryImpl.java
@@ -32,6 +32,7 @@ import java.util.concurrent.RejectedExecutionException;
 import java.util.concurrent.ScheduledExecutorService;
 import java.util.concurrent.TimeUnit;
 import java.util.concurrent.TimeoutException;
+import java.util.concurrent.atomic.AtomicReference;
 import java.util.function.BiConsumer;
 import lombok.extern.slf4j.Slf4j;
 import org.apache.pulsar.broker.PulsarServerException;
@@ -69,10 +70,12 @@ public class BrokerRegistryImpl implements BrokerRegistry {
         Init,
         Started,
         Registered,
+        Unregistering,
         Closed
     }
 
-    private State state;
+    @VisibleForTesting
+    final AtomicReference<State> state = new AtomicReference<>(State.Init);
 
     public BrokerRegistryImpl(PulsarService pulsar) {
         this.pulsar = pulsar;
@@ -80,6 +83,13 @@ public class BrokerRegistryImpl implements BrokerRegistry {
         this.brokerLookupDataMetadataCache = pulsar.getLocalMetadataStore().getMetadataCache(BrokerLookupData.class);
         this.scheduler = pulsar.getLoadManagerExecutor();
         this.listeners = new ArrayList<>();
+        // The registered node is an ephemeral node that could be deleted when the metadata store client's session
+        // is expired. In this case, we should register again.
+        this.listeners.add((broker, notificationType) -> {
+            if (notificationType == NotificationType.Deleted && getBrokerId().equals(broker)) {
+                registerAsync();
+            }
+        });
         this.brokerIdKeyPath = keyPath(pulsar.getBrokerId());
         this.brokerLookupData = new BrokerLookupData(
                 pulsar.getWebServiceAddress(),
@@ -93,44 +103,45 @@ public class BrokerRegistryImpl implements BrokerRegistry {
                 conf.getLoadManagerClassName(),
                 System.currentTimeMillis(),
                 pulsar.getBrokerVersion());
-        this.state = State.Init;
     }
 
     @Override
     public synchronized void start() throws PulsarServerException {
-        if (this.state != State.Init) {
-            return;
+        if (!this.state.compareAndSet(State.Init, State.Started)) {
+            throw new PulsarServerException("Cannot start the broker registry in state " + state.get());
         }
         pulsar.getLocalMetadataStore().registerListener(this::handleMetadataStoreNotification);
         try {
-            this.state = State.Started;
-            this.register();
-        } catch (MetadataStoreException e) {
-            throw new PulsarServerException(e);
+            this.registerAsync().get(conf.getMetadataStoreOperationTimeoutSeconds(), TimeUnit.SECONDS);
+        } catch (ExecutionException | InterruptedException | TimeoutException e) {
+            throw PulsarServerException.from(e);
         }
     }
 
     @Override
     public boolean isStarted() {
-        return this.state == State.Started || this.state == State.Registered;
+        final var state = this.state.get();
+        return state == State.Started || state == State.Registered;
     }
 
     @Override
-    public synchronized void register() throws MetadataStoreException {
-        if (this.state == State.Started) {
-            try {
-                brokerLookupDataMetadataCache.put(brokerIdKeyPath, brokerLookupData, EnumSet.of(CreateOption.Ephemeral))
-                        .get(conf.getMetadataStoreOperationTimeoutSeconds(), TimeUnit.SECONDS);
-                this.state = State.Registered;
-            } catch (InterruptedException | ExecutionException | TimeoutException e) {
-                throw MetadataStoreException.unwrap(e);
-            }
+    public CompletableFuture<Void> registerAsync() {
+        final var state = this.state.get();
+        if (state != State.Started && state != State.Registered) {
+            log.info("[{}] Skip registering self because the state is {}", getBrokerId(), state);
+            return CompletableFuture.completedFuture(null);
         }
+        log.info("[{}] Started registering self to {} (state: {})", getBrokerId(), brokerIdKeyPath, state);
+        return brokerLookupDataMetadataCache.put(brokerIdKeyPath, brokerLookupData, EnumSet.of(CreateOption.Ephemeral))
+                .thenAccept(__ -> {
+                    this.state.set(State.Registered);
+                    log.info("[{}] Finished registering self", getBrokerId());
+                });
     }
 
     @Override
     public synchronized void unregister() throws MetadataStoreException {
-        if (this.state == State.Registered) {
+        if (state.compareAndSet(State.Registered, State.Unregistering)) {
             try {
                 brokerLookupDataMetadataCache.delete(brokerIdKeyPath)
                         .get(conf.getMetadataStoreOperationTimeoutSeconds(), TimeUnit.SECONDS);
@@ -143,7 +154,7 @@ public class BrokerRegistryImpl implements BrokerRegistry {
             } catch (InterruptedException | TimeoutException e) {
                 throw MetadataStoreException.unwrap(e);
             } finally {
-                this.state = State.Started;
+                state.set(State.Started);
             }
         }
     }
@@ -190,7 +201,7 @@ public class BrokerRegistryImpl implements BrokerRegistry {
 
     @Override
     public synchronized void close() throws PulsarServerException {
-        if (this.state == State.Closed) {
+        if (this.state.get() == State.Closed) {
             return;
         }
         try {
@@ -199,7 +210,7 @@ public class BrokerRegistryImpl implements BrokerRegistry {
         } catch (Exception ex) {
             log.error("Unexpected error when unregistering the broker registry", ex);
         } finally {
-            this.state = State.Closed;
+            this.state.set(State.Closed);
         }
     }
 
@@ -237,7 +248,7 @@ public class BrokerRegistryImpl implements BrokerRegistry {
     }
 
     private void checkState() throws IllegalStateException {
-        if (this.state == State.Closed) {
+        if (this.state.get() == State.Closed) {
             throw new IllegalStateException("The registry already closed.");
         }
     }
diff --git a/pulsar-broker/src/test/java/org/apache/pulsar/broker/loadbalance/extensions/BrokerRegistryIntegrationTest.java b/pulsar-broker/src/test/java/org/apache/pulsar/broker/loadbalance/extensions/BrokerRegistryIntegrationTest.java
new file mode 100644
index 00000000000..162ea50829d
--- /dev/null
+++ b/pulsar-broker/src/test/java/org/apache/pulsar/broker/loadbalance/extensions/BrokerRegistryIntegrationTest.java
@@ -0,0 +1,124 @@
+/*
+ * 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.pulsar.broker.loadbalance.extensions;
+
+import java.time.Duration;
+import java.util.Collections;
+import java.util.List;
+import java.util.Optional;
+import lombok.extern.slf4j.Slf4j;
+import org.apache.bookkeeper.util.PortManager;
+import org.apache.pulsar.broker.PulsarService;
+import org.apache.pulsar.broker.ServiceConfiguration;
+import org.apache.pulsar.broker.loadbalance.LoadManager;
+import org.apache.pulsar.common.policies.data.ClusterData;
+import org.apache.pulsar.common.policies.data.TenantInfo;
+import org.apache.pulsar.zookeeper.LocalBookkeeperEnsemble;
+import org.awaitility.Awaitility;
+import org.testng.Assert;
+import org.testng.annotations.AfterClass;
+import org.testng.annotations.BeforeClass;
+import org.testng.annotations.Test;
+
+@Slf4j
+@Test(groups = "broker")
+public class BrokerRegistryIntegrationTest {
+
+    private static final String clusterName = "test";
+    private final int zkPort = PortManager.nextFreePort();
+    private final LocalBookkeeperEnsemble bk = new LocalBookkeeperEnsemble(2, zkPort, PortManager::nextFreePort);
+    private PulsarService pulsar;
+    private BrokerRegistry brokerRegistry;
+    private String brokerMetadataPath;
+
+    @BeforeClass
+    protected void setup() throws Exception {
+        bk.start();
+        pulsar = new PulsarService(brokerConfig());
+        pulsar.start();
+        final var admin = pulsar.getAdminClient();
+        admin.clusters().createCluster(clusterName, ClusterData.builder().build());
+        admin.tenants().createTenant("public", TenantInfo.builder()
+                .allowedClusters(Collections.singleton(clusterName)).build());
+        admin.namespaces().createNamespace("public/default");
+        brokerRegistry = ((ExtensibleLoadManagerWrapper) pulsar.getLoadManager().get()).get().getBrokerRegistry();
+        brokerMetadataPath = LoadManager.LOADBALANCE_BROKERS_ROOT + "/" + pulsar.getBrokerId();
+    }
+
+    @AfterClass(alwaysRun = true)
+    protected void cleanup() throws Exception {
+        if (pulsar != null) {
+            pulsar.close();
+        }
+        bk.stop();
+    }
+
+    @Test
+    public void testRecoverFromNodeDeletion() throws Exception {
+        // Simulate the case that the node was somehow deleted (e.g. by session timeout)
+        Awaitility.await().atMost(Duration.ofSeconds(3)).untilAsserted(() -> Assert.assertEquals(
+                brokerRegistry.getAvailableBrokersAsync().join(), List.of(pulsar.getBrokerId())));
+        pulsar.getLocalMetadataStore().delete(brokerMetadataPath, Optional.empty());
+        Awaitility.await().atMost(Duration.ofSeconds(3)).untilAsserted(() -> Assert.assertEquals(
+                brokerRegistry.getAvailableBrokersAsync().join(), List.of(pulsar.getBrokerId())));
+
+        // If the node is deleted by unregister(), it should not recreate the path
+        brokerRegistry.unregister();
+        Thread.sleep(3000);
+        Assert.assertTrue(brokerRegistry.getAvailableBrokersAsync().get().isEmpty());
+
+        // Restore the normal state
+        brokerRegistry.registerAsync().get();
+        Assert.assertEquals(brokerRegistry.getAvailableBrokersAsync().get(), List.of(pulsar.getBrokerId()));
+    }
+
+    @Test
+    public void testRegisterAgain() throws Exception {
+        Awaitility.await().atMost(Duration.ofSeconds(3)).untilAsserted(() -> Assert.assertEquals(
+                brokerRegistry.getAvailableBrokersAsync().join(), List.of(pulsar.getBrokerId())));
+        final var metadataStore = pulsar.getLocalMetadataStore();
+        final var oldResult = metadataStore.get(brokerMetadataPath).get().orElseThrow();
+        log.info("Old result: {} {}", new String(oldResult.getValue()), oldResult.getStat().getVersion());
+        brokerRegistry.registerAsync().get();
+
+        Awaitility.await().atMost(Duration.ofSeconds(3)).untilAsserted(() -> {
+            final var newResult = metadataStore.get(brokerMetadataPath).get().orElseThrow();
+            log.info("New result: {} {}", new String(newResult.getValue()), newResult.getStat().getVersion());
+            Assert.assertTrue(newResult.getStat().getVersion() > oldResult.getStat().getVersion());
+            Assert.assertEquals(newResult.getValue(), oldResult.getValue());
+        });
+    }
+
+    private ServiceConfiguration brokerConfig() {
+        final var config = new ServiceConfiguration();
+        config.setClusterName(clusterName);
+        config.setAdvertisedAddress("localhost");
+        config.setBrokerServicePort(Optional.of(0));
+        config.setWebServicePort(Optional.of(0));
+        config.setMetadataStoreUrl("zk:127.0.0.1:" + bk.getZookeeperPort());
+        config.setManagedLedgerDefaultWriteQuorum(1);
+        config.setManagedLedgerDefaultAckQuorum(1);
+        config.setManagedLedgerDefaultEnsembleSize(1);
+        config.setDefaultNumberOfNamespaceBundles(16);
+        config.setLoadManagerClassName(ExtensibleLoadManagerImpl.class.getName());
+        config.setLoadBalancerDebugModeEnabled(true);
+        config.setBrokerShutdownTimeoutMs(100);
+        return config;
+    }
+}
diff --git a/pulsar-broker/src/test/java/org/apache/pulsar/broker/loadbalance/extensions/BrokerRegistryTest.java b/pulsar-broker/src/test/java/org/apache/pulsar/broker/loadbalance/extensions/BrokerRegistryTest.java
index 91ada90dda6..28a2a18500f 100644
--- a/pulsar-broker/src/test/java/org/apache/pulsar/broker/loadbalance/extensions/BrokerRegistryTest.java
+++ b/pulsar-broker/src/test/java/org/apache/pulsar/broker/loadbalance/extensions/BrokerRegistryTest.java
@@ -332,7 +332,7 @@ public class BrokerRegistryTest {
         assertEquals(getState(brokerRegistry), BrokerRegistryImpl.State.Started);
 
         // Check state after re-register.
-        brokerRegistry.register();
+        brokerRegistry.registerAsync().get();
         assertEquals(getState(brokerRegistry), BrokerRegistryImpl.State.Registered);
 
         // Check state after close.
@@ -396,8 +396,8 @@ public class BrokerRegistryTest {
         assertEquals(keyPath, LOADBALANCE_BROKERS_ROOT + "/brokerId");
     }
 
-    public BrokerRegistryImpl.State getState(BrokerRegistryImpl brokerRegistry) {
-        return WhiteboxImpl.getInternalState(brokerRegistry, BrokerRegistryImpl.State.class);
+    private static BrokerRegistryImpl.State getState(BrokerRegistryImpl brokerRegistry) {
+        return brokerRegistry.state.get();
     }
 }
 
diff --git a/pulsar-broker/src/test/java/org/apache/pulsar/broker/loadbalance/extensions/ExtensibleLoadManagerImplTest.java b/pulsar-broker/src/test/java/org/apache/pulsar/broker/loadbalance/extensions/ExtensibleLoadManagerImplTest.java
index f2d5a682510..7580c165a50 100644
--- a/pulsar-broker/src/test/java/org/apache/pulsar/broker/loadbalance/extensions/ExtensibleLoadManagerImplTest.java
+++ b/pulsar-broker/src/test/java/org/apache/pulsar/broker/loadbalance/extensions/ExtensibleLoadManagerImplTest.java
@@ -1181,7 +1181,7 @@ public class ExtensibleLoadManagerImplTest extends ExtensibleLoadManagerImplBase
                     producer.send("t1");
 
                     // Test re-register broker and check the lookup result
-                    loadManager4.getBrokerRegistry().register();
+                    loadManager4.getBrokerRegistry().registerAsync().get();
 
                     result = pulsar.getAdminClient().lookups().lookupTopic(slaMonitorTopic);
                     assertNotNull(result);


(pulsar) 03/09: [fix][misc] Log Conscrypt security provider initialization warnings at debug level (#23364)

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

lhotari pushed a commit to branch branch-3.3
in repository https://gitbox.apache.org/repos/asf/pulsar.git

commit 57304ed1706098ef53a5a16af5e7339de272a47e
Author: Lari Hotari <lh...@users.noreply.github.com>
AuthorDate: Sun Sep 29 06:28:06 2024 +0300

    [fix][misc] Log Conscrypt security provider initialization warnings at debug level (#23364)
    
    (cherry picked from commit 950309b57a3674c43e2168168cdb9ef670ac6274)
---
 .../main/java/org/apache/pulsar/common/util/SecurityUtility.java  | 8 ++++----
 1 file changed, 4 insertions(+), 4 deletions(-)

diff --git a/pulsar-common/src/main/java/org/apache/pulsar/common/util/SecurityUtility.java b/pulsar-common/src/main/java/org/apache/pulsar/common/util/SecurityUtility.java
index 8c1f1f5d8b3..2b7b1a98463 100644
--- a/pulsar-common/src/main/java/org/apache/pulsar/common/util/SecurityUtility.java
+++ b/pulsar-common/src/main/java/org/apache/pulsar/common/util/SecurityUtility.java
@@ -133,12 +133,12 @@ public class SecurityUtility {
             conscryptClazz.getMethod("checkAvailability").invoke(null);
         } catch (Throwable e) {
             if (e instanceof ClassNotFoundException) {
-                log.warn("Conscrypt isn't available in the classpath. Using JDK default security provider.");
+                log.debug("Conscrypt isn't available in the classpath. Using JDK default security provider.");
             } else if (e.getCause() instanceof UnsatisfiedLinkError) {
-                log.warn("Conscrypt isn't available for {} {}. Using JDK default security provider.",
+                log.debug("Conscrypt isn't available for {} {}. Using JDK default security provider.",
                         System.getProperty("os.name"), System.getProperty("os.arch"));
             } else {
-                log.warn("Conscrypt isn't available. Using JDK default security provider."
+                log.debug("Conscrypt isn't available. Using JDK default security provider."
                         + " Cause : {}, Reason : {}", e.getCause(), e.getMessage());
             }
             return null;
@@ -148,7 +148,7 @@ public class SecurityUtility {
         try {
             provider = (Provider) Class.forName(CONSCRYPT_PROVIDER_CLASS).getDeclaredConstructor().newInstance();
         } catch (ReflectiveOperationException e) {
-            log.warn("Unable to get security provider for class {}", CONSCRYPT_PROVIDER_CLASS, e);
+            log.debug("Unable to get security provider for class {}", CONSCRYPT_PROVIDER_CLASS, e);
             return null;
         }
 


(pulsar) 01/09: [fix] [log] Do not print error log if tenant/namespace does not exist when calling get topic metadata (#23291)

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

lhotari pushed a commit to branch branch-3.3
in repository https://gitbox.apache.org/repos/asf/pulsar.git

commit 63ca5ecb9e1bc9c6781d2fe8ef29f65f52a4f592
Author: fengyubiao <yu...@streamnative.io>
AuthorDate: Fri Sep 27 16:34:19 2024 +0800

    [fix] [log] Do not print error log if tenant/namespace does not exist when calling get topic metadata (#23291)
    
    (cherry picked from commit 5583102aae135f5f62884f83e1ddd927b24ee737)
---
 .../apache/pulsar/broker/service/ServerCnx.java    | 41 ++++++++++++++---
 .../broker/admin/GetPartitionMetadataTest.java     | 51 ++++++++++++++++++++++
 2 files changed, 85 insertions(+), 7 deletions(-)

diff --git a/pulsar-broker/src/main/java/org/apache/pulsar/broker/service/ServerCnx.java b/pulsar-broker/src/main/java/org/apache/pulsar/broker/service/ServerCnx.java
index e846d144d58..c98caa874c7 100644
--- a/pulsar-broker/src/main/java/org/apache/pulsar/broker/service/ServerCnx.java
+++ b/pulsar-broker/src/main/java/org/apache/pulsar/broker/service/ServerCnx.java
@@ -62,6 +62,8 @@ import java.util.regex.Pattern;
 import java.util.stream.Collectors;
 import javax.naming.AuthenticationException;
 import javax.net.ssl.SSLSession;
+import javax.ws.rs.WebApplicationException;
+import javax.ws.rs.core.Response;
 import org.apache.bookkeeper.mledger.AsyncCallbacks;
 import org.apache.bookkeeper.mledger.Entry;
 import org.apache.bookkeeper.mledger.ManagedLedgerException;
@@ -660,8 +662,6 @@ public class ServerCnx extends PulsarHandler implements TransportCnx {
                                             commandSender.sendPartitionMetadataResponse(ServerError.AuthorizationError,
                                                     ex.getMessage(), requestId);
                                         } else {
-                                            log.warn("Failed to get Partitioned Metadata [{}] {}: {}", remoteAddress,
-                                                    topicName, ex.getMessage(), ex);
                                             ServerError error = ServerError.ServiceNotReady;
                                             if (ex instanceof MetadataStoreException) {
                                                 error = ServerError.MetadataError;
@@ -673,6 +673,14 @@ public class ServerCnx extends PulsarHandler implements TransportCnx {
                                                     error = ServerError.MetadataError;
                                                 }
                                             }
+                                            if (error == ServerError.TopicNotFound) {
+                                                log.info("Trying to get Partitioned Metadata for a resource not exist"
+                                                                + "[{}] {}: {}", remoteAddress,
+                                                        topicName, ex.getMessage());
+                                            } else {
+                                                log.warn("Failed to get Partitioned Metadata [{}] {}: {}",
+                                                        remoteAddress, topicName, ex.getMessage(), ex);
+                                            }
                                             commandSender.sendPartitionMetadataResponse(error, ex.getMessage(),
                                                     requestId);
                                         }
@@ -690,6 +698,16 @@ public class ServerCnx extends PulsarHandler implements TransportCnx {
                 return null;
             }).exceptionally(ex -> {
                 logAuthException(remoteAddress, "partition-metadata", getPrincipal(), Optional.of(topicName), ex);
+                Throwable actEx = FutureUtil.unwrapCompletionException(ex);
+                if (actEx instanceof WebApplicationException restException) {
+                    if (restException.getResponse().getStatus() == Response.Status.NOT_FOUND.getStatusCode()) {
+                        writeAndFlush(Commands.newPartitionMetadataResponse(ServerError.MetadataError,
+                        "Tenant or namespace or topic does not exist: " + topicName.getNamespace() ,
+                                requestId));
+                        lookupSemaphore.release();
+                        return null;
+                    }
+                }
                 final String msg = "Exception occurred while trying to authorize get Partition Metadata";
                 writeAndFlush(Commands.newPartitionMetadataResponse(ServerError.AuthorizationError, msg,
                         requestId));
@@ -3661,13 +3679,22 @@ public class ServerCnx extends PulsarHandler implements TransportCnx {
     private static void logAuthException(SocketAddress remoteAddress, String operation,
                                          String principal, Optional<TopicName> topic, Throwable ex) {
         String topicString = topic.map(t -> ", topic=" + t.toString()).orElse("");
-        if (ex instanceof AuthenticationException) {
+        Throwable actEx = FutureUtil.unwrapCompletionException(ex);
+        if (actEx instanceof AuthenticationException) {
             log.info("[{}] Failed to authenticate: operation={}, principal={}{}, reason={}",
-                    remoteAddress, operation, principal, topicString, ex.getMessage());
-        } else {
-            log.error("[{}] Error trying to authenticate: operation={}, principal={}{}",
-                    remoteAddress, operation, principal, topicString, ex);
+                    remoteAddress, operation, principal, topicString, actEx.getMessage());
+            return;
+        } else if (actEx instanceof WebApplicationException restException){
+            // Do not print error log if users tries to access a not found resource.
+            if (restException.getResponse().getStatus() == Response.Status.NOT_FOUND.getStatusCode()) {
+                log.info("[{}] Trying to authenticate for a topic which under a namespace not exists: operation={},"
+                                + " principal={}{}, reason: {}",
+                        remoteAddress, operation, principal, topicString, actEx.getMessage());
+                return;
+            }
         }
+        log.error("[{}] Error trying to authenticate: operation={}, principal={}{}",
+                remoteAddress, operation, principal, topicString, ex);
     }
 
     private static void logNamespaceNameAuthException(SocketAddress remoteAddress, String operation,
diff --git a/pulsar-broker/src/test/java/org/apache/pulsar/broker/admin/GetPartitionMetadataTest.java b/pulsar-broker/src/test/java/org/apache/pulsar/broker/admin/GetPartitionMetadataTest.java
index 87bc4267b48..e9a639697d9 100644
--- a/pulsar-broker/src/test/java/org/apache/pulsar/broker/admin/GetPartitionMetadataTest.java
+++ b/pulsar-broker/src/test/java/org/apache/pulsar/broker/admin/GetPartitionMetadataTest.java
@@ -578,4 +578,55 @@ public class GetPartitionMetadataTest {
             assertEquals(getLookupRequestPermits(), lookupPermitsBefore);
         });
     }
+
+    @Test(dataProvider = "topicDomains")
+    public void testNamespaceNotExist(TopicDomain topicDomain) throws Exception {
+        int lookupPermitsBefore = getLookupRequestPermits();
+        final String namespaceNotExist = BrokerTestUtil.newUniqueName("public/ns");
+        final String topicNameStr = BrokerTestUtil.newUniqueName(topicDomain.toString() + "://" + namespaceNotExist + "/tp");
+        PulsarClientImpl[] clientArray = getClientsToTest(false);
+        for (PulsarClientImpl client : clientArray) {
+            try {
+                PartitionedTopicMetadata topicMetadata = client
+                        .getPartitionedTopicMetadata(topicNameStr, true, true)
+                        .join();
+                log.info("Get topic metadata: {}", topicMetadata.partitions);
+                fail("Expected a not found ex");
+            } catch (Exception ex) {
+                Throwable unwrapEx = FutureUtil.unwrapCompletionException(ex);
+                assertTrue(unwrapEx instanceof PulsarClientException.BrokerMetadataException ||
+                        unwrapEx instanceof PulsarClientException.TopicDoesNotExistException);
+            }
+        }
+        // Verify: lookup semaphore has been releases.
+        Awaitility.await().untilAsserted(() -> {
+            assertEquals(getLookupRequestPermits(), lookupPermitsBefore);
+        });
+    }
+
+    @Test(dataProvider = "topicDomains")
+    public void testTenantNotExist(TopicDomain topicDomain) throws Exception {
+        int lookupPermitsBefore = getLookupRequestPermits();
+        final String tenantNotExist = BrokerTestUtil.newUniqueName("tenant");
+        final String namespaceNotExist = BrokerTestUtil.newUniqueName(tenantNotExist + "/default");
+        final String topicNameStr = BrokerTestUtil.newUniqueName(topicDomain.toString() + "://" + namespaceNotExist + "/tp");
+        PulsarClientImpl[] clientArray = getClientsToTest(false);
+        for (PulsarClientImpl client : clientArray) {
+            try {
+                PartitionedTopicMetadata topicMetadata = client
+                        .getPartitionedTopicMetadata(topicNameStr, true, true)
+                        .join();
+                log.info("Get topic metadata: {}", topicMetadata.partitions);
+                fail("Expected a not found ex");
+            } catch (Exception ex) {
+                Throwable unwrapEx = FutureUtil.unwrapCompletionException(ex);
+                assertTrue(unwrapEx instanceof PulsarClientException.BrokerMetadataException ||
+                        unwrapEx instanceof PulsarClientException.TopicDoesNotExistException);
+            }
+        }
+        // Verify: lookup semaphore has been releases.
+        Awaitility.await().untilAsserted(() -> {
+            assertEquals(getLookupRequestPermits(), lookupPermitsBefore);
+        });
+    }
 }


(pulsar) 04/09: [improve] Install openssl in the docker image to fix compatibility with Apache Pulsar Helm chart (#23362)

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

lhotari pushed a commit to branch branch-3.3
in repository https://gitbox.apache.org/repos/asf/pulsar.git

commit bc578e07cadb2982e8bec49f00080038dfeffe9f
Author: Lari Hotari <lh...@users.noreply.github.com>
AuthorDate: Sun Sep 29 20:09:54 2024 +0300

    [improve] Install openssl in the docker image to fix compatibility with Apache Pulsar Helm chart (#23362)
    
    (cherry picked from commit 7e59bdeb9d142430c7119346a34c488045271c19)
---
 docker/pulsar/Dockerfile | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)

diff --git a/docker/pulsar/Dockerfile b/docker/pulsar/Dockerfile
index b4294dd10da..2957e1587e9 100644
--- a/docker/pulsar/Dockerfile
+++ b/docker/pulsar/Dockerfile
@@ -94,7 +94,8 @@ RUN apk add --no-cache \
             ca-certificates \
             procps \
             curl \
-            bind-tools
+            bind-tools \
+            openssl
 
 # Upgrade all packages to get latest versions with security fixes
 RUN apk upgrade --no-cache


(pulsar) 09/09: [fix][broker] Fix out-of-order issues with ConsistentHashingStickyKeyConsumerSelector (#23327)

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

lhotari pushed a commit to branch branch-3.3
in repository https://gitbox.apache.org/repos/asf/pulsar.git

commit 43aabfc720912a2773fac91e4061460b335d2a73
Author: Lari Hotari <lh...@users.noreply.github.com>
AuthorDate: Wed Oct 2 11:13:36 2024 +0300

    [fix][broker] Fix out-of-order issues with ConsistentHashingStickyKeyConsumerSelector (#23327)
    
    (cherry picked from commit adb9014dbac21afdfb5fc252ac38e07ed2d6b19c)
---
 ...ConsistentHashingStickyKeyConsumerSelector.java | 104 +++---
 .../broker/service/ConsumerIdentityWrapper.java    |  70 ++++
 .../broker/service/ConsumerNameIndexTracker.java   | 136 ++++++++
 ...istentHashingStickyKeyConsumerSelectorTest.java | 366 ++++++++++++++++++++-
 .../service/ConsumerIdentityWrapperTest.java       |  68 ++++
 .../service/ConsumerNameIndexTrackerTest.java      | 157 +++++++++
 ...ntStickyKeyDispatcherMultipleConsumersTest.java |   9 +-
 .../java/org/apache/pulsar/client/api/Range.java   |  11 +-
 8 files changed, 853 insertions(+), 68 deletions(-)

diff --git a/pulsar-broker/src/main/java/org/apache/pulsar/broker/service/ConsistentHashingStickyKeyConsumerSelector.java b/pulsar-broker/src/main/java/org/apache/pulsar/broker/service/ConsistentHashingStickyKeyConsumerSelector.java
index b2b2b512c8c..1ae9a6ff96b 100644
--- a/pulsar-broker/src/main/java/org/apache/pulsar/broker/service/ConsistentHashingStickyKeyConsumerSelector.java
+++ b/pulsar-broker/src/main/java/org/apache/pulsar/broker/service/ConsistentHashingStickyKeyConsumerSelector.java
@@ -18,10 +18,8 @@
  */
 package org.apache.pulsar.broker.service;
 
-import com.google.common.collect.Lists;
 import java.util.ArrayList;
-import java.util.Comparator;
-import java.util.LinkedHashMap;
+import java.util.IdentityHashMap;
 import java.util.List;
 import java.util.Map;
 import java.util.NavigableMap;
@@ -44,7 +42,9 @@ public class ConsistentHashingStickyKeyConsumerSelector implements StickyKeyCons
     private final ReadWriteLock rwLock = new ReentrantReadWriteLock();
 
     // Consistent-Hash ring
-    private final NavigableMap<Integer, List<Consumer>> hashRing;
+    private final NavigableMap<Integer, ConsumerIdentityWrapper> hashRing;
+    // Tracks the used consumer name indexes for each consumer name
+    private final ConsumerNameIndexTracker consumerNameIndexTracker = new ConsumerNameIndexTracker();
 
     private final int numberOfPoints;
 
@@ -57,21 +57,20 @@ public class ConsistentHashingStickyKeyConsumerSelector implements StickyKeyCons
     public CompletableFuture<Void> addConsumer(Consumer consumer) {
         rwLock.writeLock().lock();
         try {
+            ConsumerIdentityWrapper consumerIdentityWrapper = new ConsumerIdentityWrapper(consumer);
             // Insert multiple points on the hash ring for every consumer
             // The points are deterministically added based on the hash of the consumer name
             for (int i = 0; i < numberOfPoints; i++) {
-                int hash = calculateHashForConsumerAndIndex(consumer, i);
-                hashRing.compute(hash, (k, v) -> {
-                    if (v == null) {
-                        return Lists.newArrayList(consumer);
-                    } else {
-                        if (!v.contains(consumer)) {
-                            v.add(consumer);
-                            v.sort(Comparator.comparing(Consumer::consumerName, String::compareTo));
-                        }
-                        return v;
-                    }
-                });
+                int consumerNameIndex =
+                        consumerNameIndexTracker.increaseConsumerRefCountAndReturnIndex(consumerIdentityWrapper);
+                int hash = calculateHashForConsumerAndIndex(consumer, consumerNameIndex, i);
+                // When there's a collision, the new consumer will replace the old one.
+                // This is a rare case, and it is acceptable to replace the old consumer since there
+                // are multiple points for each consumer. This won't affect the overall distribution significantly.
+                ConsumerIdentityWrapper removed = hashRing.put(hash, consumerIdentityWrapper);
+                if (removed != null) {
+                    consumerNameIndexTracker.decreaseConsumerRefCount(removed);
+                }
             }
             return CompletableFuture.completedFuture(null);
         } finally {
@@ -79,8 +78,19 @@ public class ConsistentHashingStickyKeyConsumerSelector implements StickyKeyCons
         }
     }
 
-    private static int calculateHashForConsumerAndIndex(Consumer consumer, int index) {
-        String key = consumer.consumerName() + KEY_SEPARATOR + index;
+    /**
+     * Calculate the hash for a consumer and hash ring point.
+     * The hash is calculated based on the consumer name, consumer name index, and hash ring point index.
+     * The resulting hash is used as the key to insert the consumer into the hash ring.
+     *
+     * @param consumer the consumer
+     * @param consumerNameIndex the index of the consumer name
+     * @param hashRingPointIndex the index of the hash ring point
+     * @return the hash value
+     */
+    private static int calculateHashForConsumerAndIndex(Consumer consumer, int consumerNameIndex,
+                                                        int hashRingPointIndex) {
+        String key = consumer.consumerName() + KEY_SEPARATOR + consumerNameIndex + KEY_SEPARATOR + hashRingPointIndex;
         return Murmur3_32Hash.getInstance().makeHash(key.getBytes());
     }
 
@@ -88,20 +98,16 @@ public class ConsistentHashingStickyKeyConsumerSelector implements StickyKeyCons
     public void removeConsumer(Consumer consumer) {
         rwLock.writeLock().lock();
         try {
-            // Remove all the points that were added for this consumer
-            for (int i = 0; i < numberOfPoints; i++) {
-                int hash = calculateHashForConsumerAndIndex(consumer, i);
-                hashRing.compute(hash, (k, v) -> {
-                    if (v == null) {
-                        return null;
-                    } else {
-                        v.removeIf(c -> c.equals(consumer));
-                        if (v.isEmpty()) {
-                            v = null;
-                        }
-                        return v;
+            ConsumerIdentityWrapper consumerIdentityWrapper = new ConsumerIdentityWrapper(consumer);
+            int consumerNameIndex = consumerNameIndexTracker.getTrackedIndex(consumerIdentityWrapper);
+            if (consumerNameIndex > -1) {
+                // Remove all the points that were added for this consumer
+                for (int i = 0; i < numberOfPoints; i++) {
+                    int hash = calculateHashForConsumerAndIndex(consumer, consumerNameIndex, i);
+                    if (hashRing.remove(hash, consumerIdentityWrapper)) {
+                        consumerNameIndexTracker.decreaseConsumerRefCount(consumerIdentityWrapper);
                     }
-                });
+                }
             }
         } finally {
             rwLock.writeLock().unlock();
@@ -115,16 +121,13 @@ public class ConsistentHashingStickyKeyConsumerSelector implements StickyKeyCons
             if (hashRing.isEmpty()) {
                 return null;
             }
-
-            List<Consumer> consumerList;
-            Map.Entry<Integer, List<Consumer>> ceilingEntry = hashRing.ceilingEntry(hash);
+            Map.Entry<Integer, ConsumerIdentityWrapper> ceilingEntry = hashRing.ceilingEntry(hash);
             if (ceilingEntry != null) {
-                consumerList =  ceilingEntry.getValue();
+                return ceilingEntry.getValue().consumer;
             } else {
-                consumerList = hashRing.firstEntry().getValue();
+                // Handle wrap-around in the hash ring, return the first consumer
+                return hashRing.firstEntry().getValue().consumer;
             }
-
-            return consumerList.get(hash % consumerList.size());
         } finally {
             rwLock.readLock().unlock();
         }
@@ -132,16 +135,27 @@ public class ConsistentHashingStickyKeyConsumerSelector implements StickyKeyCons
 
     @Override
     public Map<Consumer, List<Range>> getConsumerKeyHashRanges() {
-        Map<Consumer, List<Range>> result = new LinkedHashMap<>();
+        Map<Consumer, List<Range>> result = new IdentityHashMap<>();
         rwLock.readLock().lock();
         try {
+            if (hashRing.isEmpty()) {
+                return result;
+            }
             int start = 0;
-            for (Map.Entry<Integer, List<Consumer>> entry: hashRing.entrySet()) {
-                for (Consumer consumer: entry.getValue()) {
-                    result.computeIfAbsent(consumer, key -> new ArrayList<>())
-                            .add(Range.of(start, entry.getKey()));
-                }
-                start = entry.getKey() + 1;
+            int lastKey = 0;
+            for (Map.Entry<Integer, ConsumerIdentityWrapper> entry: hashRing.entrySet()) {
+                Consumer consumer = entry.getValue().consumer;
+                result.computeIfAbsent(consumer, key -> new ArrayList<>())
+                        .add(Range.of(start, entry.getKey()));
+                lastKey = entry.getKey();
+                start = lastKey + 1;
+            }
+            // Handle wrap-around in the hash ring, the first consumer will also contain the range from the last key
+            // to the maximum value of the hash range
+            Consumer firstConsumer = hashRing.firstEntry().getValue().consumer;
+            List<Range> ranges = result.get(firstConsumer);
+            if (lastKey != Integer.MAX_VALUE - 1) {
+                ranges.add(Range.of(lastKey + 1, Integer.MAX_VALUE - 1));
             }
         } finally {
             rwLock.readLock().unlock();
diff --git a/pulsar-broker/src/main/java/org/apache/pulsar/broker/service/ConsumerIdentityWrapper.java b/pulsar-broker/src/main/java/org/apache/pulsar/broker/service/ConsumerIdentityWrapper.java
new file mode 100644
index 00000000000..2aae1d9b062
--- /dev/null
+++ b/pulsar-broker/src/main/java/org/apache/pulsar/broker/service/ConsumerIdentityWrapper.java
@@ -0,0 +1,70 @@
+/*
+ * 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.pulsar.broker.service;
+
+/**
+ * A wrapper class for a Consumer instance that provides custom implementations
+ * of equals and hashCode methods. The equals method returns true if and only if
+ * the compared instance is the same instance.
+ *
+ * <p>The reason for this class is the custom implementation of {@link Consumer#equals(Object)}.
+ * Using this wrapper class will be useful in use cases where it's necessary to match a key
+ * in a map by instance or a value in a set by instance.</p>
+ */
+class ConsumerIdentityWrapper {
+    final Consumer consumer;
+
+    public ConsumerIdentityWrapper(Consumer consumer) {
+        this.consumer = consumer;
+    }
+
+    /**
+     * Compares this wrapper to the specified object. The result is true if and only if
+     * the argument is not null and is a ConsumerIdentityWrapper object that wraps
+     * the same Consumer instance.
+     *
+     * @param obj the object to compare this ConsumerIdentityWrapper against
+     * @return true if the given object represents a ConsumerIdentityWrapper
+     *         equivalent to this wrapper, false otherwise
+     */
+    @Override
+    public boolean equals(Object obj) {
+        if (obj instanceof ConsumerIdentityWrapper) {
+            ConsumerIdentityWrapper other = (ConsumerIdentityWrapper) obj;
+            return consumer == other.consumer;
+        }
+        return false;
+    }
+
+    /**
+     * Returns a hash code for this wrapper. The hash code is computed based on
+     * the wrapped Consumer instance.
+     *
+     * @return a hash code value for this object
+     */
+    @Override
+    public int hashCode() {
+        return consumer.hashCode();
+    }
+
+    @Override
+    public String toString() {
+        return consumer.toString();
+    }
+}
\ No newline at end of file
diff --git a/pulsar-broker/src/main/java/org/apache/pulsar/broker/service/ConsumerNameIndexTracker.java b/pulsar-broker/src/main/java/org/apache/pulsar/broker/service/ConsumerNameIndexTracker.java
new file mode 100644
index 00000000000..1f93313ab1b
--- /dev/null
+++ b/pulsar-broker/src/main/java/org/apache/pulsar/broker/service/ConsumerNameIndexTracker.java
@@ -0,0 +1,136 @@
+/*
+ * 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.pulsar.broker.service;
+
+import java.util.HashMap;
+import java.util.Map;
+import javax.annotation.concurrent.NotThreadSafe;
+import org.apache.commons.lang3.mutable.MutableInt;
+import org.roaringbitmap.RoaringBitmap;
+
+/**
+ * Tracks the used consumer name indexes for each consumer name.
+ * This is used by {@link ConsistentHashingStickyKeyConsumerSelector} to get a unique "consumer name index"
+ * for each consumer name. It is useful when there are multiple consumers with the same name, but they are
+ * different consumers. The purpose of the index is to prevent collisions in the hash ring.
+ *
+ * The consumer name index serves as an additional key for the hash ring assignment. The logic keeps track of
+ * used "index slots" for each consumer name and assigns the first unused index when a new consumer is added.
+ * This approach minimizes hash collisions due to using the same consumer name.
+ *
+ * An added benefit of this tracking approach is that a consumer that leaves and then rejoins immediately will get the
+ * same index and therefore the same assignments in the hash ring. This improves stability since the hash assignment
+ * changes are minimized over time, although a better solution would be to avoid reusing the same consumer name
+ * in the first place.
+ *
+ * When a consumer is removed, the index is deallocated. RoaringBitmap is used to keep track of the used indexes.
+ * The data structure to track a consumer name is removed when the reference count of the consumer name is zero.
+ *
+ * This class is not thread-safe and should be used in a synchronized context in the caller.
+ */
+@NotThreadSafe
+class ConsumerNameIndexTracker {
+    // tracks the used index slots for each consumer name
+    private final Map<String, ConsumerNameIndexSlots> consumerNameIndexSlotsMap = new HashMap<>();
+    // tracks the active consumer entries
+    private final Map<ConsumerIdentityWrapper, ConsumerEntry> consumerEntries = new HashMap<>();
+
+    // Represents a consumer entry in the tracker, including the consumer name, index, and reference count.
+    record ConsumerEntry(String consumerName, int nameIndex, MutableInt refCount) {
+    }
+
+    /*
+     * Tracks the used indexes for a consumer name using a RoaringBitmap.
+     * A specific index slot is used when the bit is set.
+     * When all bits are cleared, the customer name can be removed from tracking.
+     */
+    static class ConsumerNameIndexSlots {
+        private RoaringBitmap indexSlots = new RoaringBitmap();
+
+        public int allocateIndexSlot() {
+            // find the first index that is not set, if there is no such index, add a new one
+            int index = (int) indexSlots.nextAbsentValue(0);
+            if (index == -1) {
+                index = indexSlots.getCardinality();
+            }
+            indexSlots.add(index);
+            return index;
+        }
+
+        public boolean deallocateIndexSlot(int index) {
+            indexSlots.remove(index);
+            return indexSlots.isEmpty();
+        }
+    }
+
+    /*
+     * Adds a reference to the consumer and returns the index assigned to this consumer.
+     */
+    public int increaseConsumerRefCountAndReturnIndex(ConsumerIdentityWrapper wrapper) {
+        ConsumerEntry entry = consumerEntries.computeIfAbsent(wrapper, k -> {
+            String consumerName = wrapper.consumer.consumerName();
+            return new ConsumerEntry(consumerName, allocateConsumerNameIndex(consumerName), new MutableInt(0));
+        });
+        entry.refCount.increment();
+        return entry.nameIndex;
+    }
+
+    private int allocateConsumerNameIndex(String consumerName) {
+        return getConsumerNameIndexBitmap(consumerName).allocateIndexSlot();
+    }
+
+    private ConsumerNameIndexSlots getConsumerNameIndexBitmap(String consumerName) {
+        return consumerNameIndexSlotsMap.computeIfAbsent(consumerName, k -> new ConsumerNameIndexSlots());
+    }
+
+    /*
+     * Decreases the reference count of the consumer and removes the consumer name from tracking if the ref count is
+     * zero.
+     */
+    public void decreaseConsumerRefCount(ConsumerIdentityWrapper removed) {
+        ConsumerEntry consumerEntry = consumerEntries.get(removed);
+        int refCount = consumerEntry.refCount.decrementAndGet();
+        if (refCount == 0) {
+            deallocateConsumerNameIndex(consumerEntry.consumerName, consumerEntry.nameIndex);
+            consumerEntries.remove(removed, consumerEntry);
+        }
+    }
+
+    private void deallocateConsumerNameIndex(String consumerName, int index) {
+        if (getConsumerNameIndexBitmap(consumerName).deallocateIndexSlot(index)) {
+            consumerNameIndexSlotsMap.remove(consumerName);
+        }
+    }
+
+    /*
+     * Returns the currently tracked index for the consumer.
+     */
+    public int getTrackedIndex(ConsumerIdentityWrapper wrapper) {
+        ConsumerEntry consumerEntry = consumerEntries.get(wrapper);
+        return consumerEntry != null ? consumerEntry.nameIndex : -1;
+    }
+
+    int getTrackedConsumerNamesCount() {
+        return consumerNameIndexSlotsMap.size();
+    }
+
+    int getTrackedConsumersCount() {
+        return consumerEntries.size();
+    }
+}
diff --git a/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/ConsistentHashingStickyKeyConsumerSelectorTest.java b/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/ConsistentHashingStickyKeyConsumerSelectorTest.java
index 48311c57338..04aafc49b47 100644
--- a/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/ConsistentHashingStickyKeyConsumerSelectorTest.java
+++ b/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/ConsistentHashingStickyKeyConsumerSelectorTest.java
@@ -18,19 +18,27 @@
  */
 package org.apache.pulsar.broker.service;
 
+import static org.assertj.core.api.Assertions.assertThat;
 import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.when;
-
+import java.nio.charset.StandardCharsets;
 import java.util.ArrayList;
 import java.util.Arrays;
+import java.util.Collections;
+import java.util.Comparator;
 import java.util.HashMap;
+import java.util.HashSet;
 import java.util.List;
 import java.util.Map;
+import java.util.Set;
 import java.util.UUID;
 import java.util.stream.Collectors;
 import java.util.stream.IntStream;
+import org.apache.commons.lang3.mutable.MutableInt;
 import org.apache.pulsar.broker.service.BrokerServiceException.ConsumerAssignException;
 import org.apache.pulsar.client.api.Range;
+import org.assertj.core.data.Offset;
+import org.mockito.Mockito;
 import org.testng.Assert;
 import org.testng.annotations.Test;
 
@@ -40,7 +48,7 @@ public class ConsistentHashingStickyKeyConsumerSelectorTest {
     @Test
     public void testConsumerSelect() throws ConsumerAssignException {
 
-        ConsistentHashingStickyKeyConsumerSelector selector = new ConsistentHashingStickyKeyConsumerSelector(100);
+        ConsistentHashingStickyKeyConsumerSelector selector = new ConsistentHashingStickyKeyConsumerSelector(200);
         String key1 = "anyKey";
         Assert.assertNull(selector.select(key1.getBytes()));
 
@@ -146,31 +154,115 @@ public class ConsistentHashingStickyKeyConsumerSelectorTest {
         ConsistentHashingStickyKeyConsumerSelector selector = new ConsistentHashingStickyKeyConsumerSelector(3);
         List<String> consumerName = Arrays.asList("consumer1", "consumer2", "consumer3");
         List<Consumer> consumers = new ArrayList<>();
+        long id=0;
         for (String s : consumerName) {
-            Consumer consumer = mock(Consumer.class);
-            when(consumer.consumerName()).thenReturn(s);
+            Consumer consumer = createMockConsumer(s, s, id++);
             selector.addConsumer(consumer);
             consumers.add(consumer);
         }
+
+        // check that results are the same when called multiple times
+        assertThat(selector.getConsumerKeyHashRanges())
+                .containsExactlyEntriesOf(selector.getConsumerKeyHashRanges());
+
         Map<Consumer, List<Range>> expectedResult = new HashMap<>();
+        assertThat(consumers.get(0).consumerName()).isEqualTo("consumer1");
         expectedResult.put(consumers.get(0), Arrays.asList(
-                Range.of(119056335, 242013991),
-                Range.of(722195657, 1656011842),
-                Range.of(1707482098, 1914695766)));
+                Range.of(95615213, 440020355),
+                Range.of(440020356, 455987436),
+                Range.of(1189794593, 1264144431)));
+        assertThat(consumers.get(1).consumerName()).isEqualTo("consumer2");
         expectedResult.put(consumers.get(1), Arrays.asList(
-                Range.of(0, 90164503),
-                Range.of(90164504, 119056334),
-                Range.of(382436668, 722195656)));
+                Range.of(939655188, 1189794592),
+                Range.of(1314727625, 1977451233),
+                Range.of(1977451234, 2016237253)));
+        assertThat(consumers.get(2).consumerName()).isEqualTo("consumer3");
         expectedResult.put(consumers.get(2), Arrays.asList(
-                Range.of(242013992, 242377547),
-                Range.of(242377548, 382436667),
-                Range.of(1656011843, 1707482097)));
-        for (Map.Entry<Consumer, List<Range>> entry : selector.getConsumerKeyHashRanges().entrySet()) {
-            System.out.println(entry.getValue());
-            Assert.assertEquals(entry.getValue(), expectedResult.get(entry.getKey()));
-            expectedResult.remove(entry.getKey());
+                Range.of(0, 95615212),
+                Range.of(455987437, 939655187),
+                Range.of(1264144432, 1314727624),
+                Range.of(2016237254, 2147483646)));
+        Map<Consumer, List<Range>> consumerKeyHashRanges = selector.getConsumerKeyHashRanges();
+        assertThat(consumerKeyHashRanges).containsExactlyInAnyOrderEntriesOf(expectedResult);
+
+        // check that ranges are continuous and cover the whole range
+        List<Range> allRanges =
+                consumerKeyHashRanges.values().stream().flatMap(List::stream).sorted().collect(Collectors.toList());
+        Range previousRange = null;
+        for (Range range : allRanges) {
+            if (previousRange != null) {
+                assertThat(range.getStart()).isEqualTo(previousRange.getEnd() + 1);
+            }
+            previousRange = range;
+        }
+        assertThat(allRanges.stream().mapToInt(r -> r.getEnd() - r.getStart() + 1).sum()).isEqualTo(Integer.MAX_VALUE);
+    }
+
+    @Test
+    public void testConsumersGetSufficientlyAccuratelyEvenlyMapped()
+            throws BrokerServiceException.ConsumerAssignException {
+        ConsistentHashingStickyKeyConsumerSelector selector = new ConsistentHashingStickyKeyConsumerSelector(200);
+        List<Consumer> consumers = new ArrayList<>();
+        for (int i = 0; i < 20; i++) {
+            // use the same name for all consumers, use toString to distinguish them
+            Consumer consumer = createMockConsumer("consumer", String.format("index %02d", i), i);
+            selector.addConsumer(consumer);
+            consumers.add(consumer);
         }
-        Assert.assertEquals(expectedResult.size(), 0);
+        printConsumerRangesStats(selector);
+
+        int totalSelections = 10000;
+
+        Map<Consumer, MutableInt> consumerSelectionCount = new HashMap<>();
+        for (int i = 0; i < totalSelections; i++) {
+            Consumer selectedConsumer = selector.select(("key " + i).getBytes(StandardCharsets.UTF_8));
+            consumerSelectionCount.computeIfAbsent(selectedConsumer, c -> new MutableInt()).increment();
+        }
+
+        printSelectionCountStats(consumerSelectionCount);
+
+        int averageCount = totalSelections / consumers.size();
+        int allowedVariance = (int) (0.2d * averageCount);
+        System.out.println("averageCount: " + averageCount + " allowedVariance: " + allowedVariance);
+
+        for (Map.Entry<Consumer, MutableInt> entry : consumerSelectionCount.entrySet()) {
+            assertThat(entry.getValue().intValue()).describedAs("consumer: %s", entry.getKey())
+                    .isCloseTo(averageCount, Offset.offset(allowedVariance));
+        }
+
+        consumers.forEach(selector::removeConsumer);
+        assertThat(selector.getConsumerKeyHashRanges()).isEmpty();
+    }
+
+    private static void printSelectionCountStats(Map<Consumer, MutableInt> consumerSelectionCount) {
+        int totalSelections = consumerSelectionCount.values().stream().mapToInt(MutableInt::intValue).sum();
+        consumerSelectionCount.entrySet().stream()
+                .sorted(Map.Entry.comparingByKey(Comparator.comparing(Consumer::toString)))
+                .forEach(entry -> System.out.println(
+                        String.format("consumer: %s got selected %d times. ratio: %.2f%%", entry.getKey(),
+                                entry.getValue().intValue(),
+                                ((double) entry.getValue().intValue() / totalSelections) * 100.0d)));
+    }
+
+    private static void printConsumerRangesStats(ConsistentHashingStickyKeyConsumerSelector selector) {
+        selector.getConsumerKeyHashRanges().entrySet().stream()
+                .map(entry -> Map.entry(entry.getKey(),
+                        entry.getValue().stream().mapToInt(r -> r.getEnd() - r.getStart() + 1).sum()))
+                .sorted(Map.Entry.comparingByKey(Comparator.comparing(Consumer::toString)))
+                .forEach(entry -> System.out.println(
+                        String.format("consumer: %s total ranges size: %d ratio: %.2f%%", entry.getKey(),
+                                entry.getValue(),
+                                ((double) entry.getValue() / (Integer.MAX_VALUE - 1)) * 100.0d)));
+    }
+
+    private static Consumer createMockConsumer(String consumerName, String toString, long id) {
+        // without stubOnly, the mock will record method invocations and run into OOME
+        Consumer consumer =  mock(Consumer.class, Mockito.withSettings().stubOnly());
+        when(consumer.consumerName()).thenReturn(consumerName);
+        when(consumer.getPriorityLevel()).thenReturn(0);
+        when(consumer.toString()).thenReturn(toString);
+        when(consumer.consumerId()).thenReturn(id);
+        return consumer;
     }
 
     // reproduces https://github.com/apache/pulsar/issues/22050
@@ -215,5 +307,243 @@ public class ConsistentHashingStickyKeyConsumerSelectorTest {
         consumers.forEach(selector::removeConsumer);
         // then there should be no mapping remaining
         Assert.assertEquals(selector.getConsumerKeyHashRanges().size(), 0);
+        // when consumers are removed again, should not fail
+        consumers.forEach(selector::removeConsumer);
+    }
+
+    @Test
+    public void testShouldNotChangeSelectedConsumerWhenConsumerIsRemoved() {
+        final ConsistentHashingStickyKeyConsumerSelector selector = new ConsistentHashingStickyKeyConsumerSelector(100);
+        final String consumerName = "consumer";
+        final int numOfInitialConsumers = 100;
+        List<Consumer> consumers = new ArrayList<>();
+        for (int i = 0; i < numOfInitialConsumers; i++) {
+            final Consumer consumer = createMockConsumer(consumerName, "index " + i, i);
+            consumers.add(consumer);
+            selector.addConsumer(consumer);
+        }
+
+        int hashRangeSize = Integer.MAX_VALUE;
+        int validationPointCount = 200;
+        int increment = hashRangeSize / (validationPointCount + 1);
+        List<Consumer> selectedConsumerBeforeRemoval = new ArrayList<>();
+
+        for (int i = 0; i < validationPointCount; i++) {
+            selectedConsumerBeforeRemoval.add(selector.select(i * increment));
+        }
+
+        for (int i = 0; i < validationPointCount; i++) {
+            Consumer selected = selector.select(i * increment);
+            Consumer expected = selectedConsumerBeforeRemoval.get(i);
+            assertThat(selected.consumerId()).as("validationPoint %d", i).isEqualTo(expected.consumerId());
+        }
+
+        Set<Consumer> removedConsumers = new HashSet<>();
+        for (Consumer removedConsumer : consumers) {
+            selector.removeConsumer(removedConsumer);
+            removedConsumers.add(removedConsumer);
+            for (int i = 0; i < validationPointCount; i++) {
+                int hash = i * increment;
+                Consumer selected = selector.select(hash);
+                Consumer expected = selectedConsumerBeforeRemoval.get(i);
+                if (!removedConsumers.contains(expected)) {
+                    assertThat(selected.consumerId()).as("validationPoint %d, removed %s, hash %d ranges %s", i,
+                            removedConsumer.toString(), hash, selector.getConsumerKeyHashRanges()).isEqualTo(expected.consumerId());
+                }
+            }
+        }
+    }
+
+    @Test
+    public void testShouldNotChangeSelectedConsumerWhenConsumerIsRemovedCheckHashRanges() {
+        final ConsistentHashingStickyKeyConsumerSelector selector = new ConsistentHashingStickyKeyConsumerSelector(100);
+        final String consumerName = "consumer";
+        final int numOfInitialConsumers = 25;
+        List<Consumer> consumers = new ArrayList<>();
+        for (int i = 0; i < numOfInitialConsumers; i++) {
+            final Consumer consumer = createMockConsumer(consumerName, "index " + i, i);
+            consumers.add(consumer);
+            selector.addConsumer(consumer);
+        }
+
+        Map<Consumer, List<Range>> expected = selector.getConsumerKeyHashRanges();
+        assertThat(selector.getConsumerKeyHashRanges()).as("sanity check").containsExactlyInAnyOrderEntriesOf(expected);
+        System.out.println(expected);
+
+        for (Consumer removedConsumer : consumers) {
+            selector.removeConsumer(removedConsumer);
+            for (Map.Entry<Consumer, List<Range>> entry : expected.entrySet()) {
+                if (entry.getKey() == removedConsumer) {
+                    continue;
+                }
+                for (Range range : entry.getValue()) {
+                    Consumer rangeStartConsumer = selector.select(range.getStart());
+                    assertThat(rangeStartConsumer).as("removed %s, range %s", removedConsumer, range)
+                            .isEqualTo(entry.getKey());
+                    Consumer rangeEndConsumer = selector.select(range.getEnd());
+                    assertThat(rangeEndConsumer).as("removed %s, range %s", removedConsumer, range)
+                            .isEqualTo(entry.getKey());
+                    assertThat(rangeStartConsumer).isSameAs(rangeEndConsumer);
+                }
+            }
+            expected = selector.getConsumerKeyHashRanges();
+        }
+    }
+
+    @Test
+    public void testShouldNotChangeSelectedConsumerUnnecessarilyWhenConsumerIsAddedCheckHashRanges() {
+        final ConsistentHashingStickyKeyConsumerSelector selector = new ConsistentHashingStickyKeyConsumerSelector(100);
+        final String consumerName = "consumer";
+        final int numOfInitialConsumers = 25;
+        List<Consumer> consumers = new ArrayList<>();
+        for (int i = 0; i < numOfInitialConsumers; i++) {
+            final Consumer consumer = createMockConsumer(consumerName, "index " + i, i);
+            consumers.add(consumer);
+            selector.addConsumer(consumer);
+        }
+
+        Map<Consumer, List<Range>> expected = selector.getConsumerKeyHashRanges();
+        assertThat(selector.getConsumerKeyHashRanges()).as("sanity check").containsExactlyInAnyOrderEntriesOf(expected);
+
+        for (int i = numOfInitialConsumers; i < numOfInitialConsumers * 2; i++) {
+            final Consumer addedConsumer = createMockConsumer(consumerName, "index " + i, i);
+            selector.addConsumer(addedConsumer);
+            for (Map.Entry<Consumer, List<Range>> entry : expected.entrySet()) {
+                if (entry.getKey() == addedConsumer) {
+                    continue;
+                }
+                for (Range range : entry.getValue()) {
+                    Consumer rangeStartConsumer = selector.select(range.getStart());
+                    if (rangeStartConsumer != addedConsumer) {
+                        assertThat(rangeStartConsumer).as("added %s, range start %s", addedConsumer, range)
+                                .isEqualTo(entry.getKey());
+                    }
+                    Consumer rangeEndConsumer = selector.select(range.getStart());
+                    if (rangeEndConsumer != addedConsumer) {
+                        assertThat(rangeEndConsumer).as("added %s, range end %s", addedConsumer, range)
+                                .isEqualTo(entry.getKey());
+                    }
+                }
+            }
+            expected = selector.getConsumerKeyHashRanges();
+        }
+    }
+
+    @Test
+    public void testShouldNotChangeSelectedConsumerWhenConsumerIsAdded() {
+        final ConsistentHashingStickyKeyConsumerSelector selector = new ConsistentHashingStickyKeyConsumerSelector(100);
+        final String consumerName = "consumer";
+        final int numOfInitialConsumers = 50;
+        List<Consumer> consumers = new ArrayList<>();
+        for (int i = 0; i < numOfInitialConsumers; i++) {
+            final Consumer consumer = createMockConsumer(consumerName, "index " + i, i);
+            consumers.add(consumer);
+            selector.addConsumer(consumer);
+        }
+
+        int hashRangeSize = Integer.MAX_VALUE;
+        int validationPointCount = 200;
+        int increment = hashRangeSize / (validationPointCount + 1);
+        List<Consumer> selectedConsumerBeforeRemoval = new ArrayList<>();
+
+        for (int i = 0; i < validationPointCount; i++) {
+            selectedConsumerBeforeRemoval.add(selector.select(i * increment));
+        }
+
+        for (int i = 0; i < validationPointCount; i++) {
+            Consumer selected = selector.select(i * increment);
+            Consumer expected = selectedConsumerBeforeRemoval.get(i);
+            assertThat(selected.consumerId()).as("validationPoint %d", i).isEqualTo(expected.consumerId());
+        }
+
+        Set<Consumer> addedConsumers = new HashSet<>();
+        for (int i = numOfInitialConsumers; i < numOfInitialConsumers * 2; i++) {
+            final Consumer addedConsumer = createMockConsumer(consumerName, "index " + i, i);
+            selector.addConsumer(addedConsumer);
+            addedConsumers.add(addedConsumer);
+            for (int j = 0; j < validationPointCount; j++) {
+                int hash = j * increment;
+                Consumer selected = selector.select(hash);
+                Consumer expected = selectedConsumerBeforeRemoval.get(j);
+                if (!addedConsumers.contains(addedConsumer)) {
+                    assertThat(selected.consumerId()).as("validationPoint %d, hash %d", j, hash).isEqualTo(expected.consumerId());
+                }
+            }
+        }
+    }
+
+    @Test
+    public void testShouldNotChangeMappingWhenConsumerLeavesAndRejoins() {
+        final ConsistentHashingStickyKeyConsumerSelector selector = new ConsistentHashingStickyKeyConsumerSelector(100);
+        final String consumerName = "consumer";
+        final int numOfInitialConsumers = 25;
+        List<Consumer> consumers = new ArrayList<>();
+        for (int i = 0; i < numOfInitialConsumers; i++) {
+            final Consumer consumer = createMockConsumer(consumerName, "index " + i, i);
+            consumers.add(consumer);
+            selector.addConsumer(consumer);
+        }
+
+        Map<Consumer, List<Range>> expected = selector.getConsumerKeyHashRanges();
+        assertThat(selector.getConsumerKeyHashRanges()).as("sanity check").containsExactlyInAnyOrderEntriesOf(expected);
+
+        selector.removeConsumer(consumers.get(0));
+        selector.removeConsumer(consumers.get(numOfInitialConsumers / 2));
+        selector.addConsumer(consumers.get(0));
+        selector.addConsumer(consumers.get(numOfInitialConsumers / 2));
+
+        assertThat(selector.getConsumerKeyHashRanges()).as("ranges shouldn't change").containsExactlyInAnyOrderEntriesOf(expected);
+    }
+
+    @Test
+    public void testConsumersReconnect() {
+        final ConsistentHashingStickyKeyConsumerSelector selector = new ConsistentHashingStickyKeyConsumerSelector(100);
+        final String consumerName = "consumer";
+        final int numOfInitialConsumers = 50;
+        final int validationPointCount = 200;
+        final List<Integer> pointsToTest = pointsToTest(validationPointCount);
+        List<Consumer> consumers = new ArrayList<>();
+        for (int i = 0; i < numOfInitialConsumers; i++) {
+            final Consumer consumer = createMockConsumer(consumerName, "index " + i, i);
+            consumers.add(consumer);
+            selector.addConsumer(consumer);
+        }
+
+        // Mark original results.
+        List<Consumer> selectedConsumersBeforeRemove = new ArrayList<>();
+        for (int i = 0; i < validationPointCount; i++) {
+            int point = pointsToTest.get(i);
+            selectedConsumersBeforeRemove.add(selector.select(point));
+        }
+
+        // All consumers leave (in any order)
+        List<Consumer> randomOrderConsumers = new ArrayList<>(consumers);
+        Collections.shuffle(randomOrderConsumers);
+        for (Consumer c : randomOrderConsumers) {
+            selector.removeConsumer(c);
+        }
+
+        // All consumers reconnect in the same order as originally
+        for (Consumer c : consumers) {
+            selector.addConsumer(c);
+        }
+
+        // Check that the same consumers are selected as before
+        for (int j = 0; j < validationPointCount; j++) {
+            int point = pointsToTest.get(j);
+            Consumer selected = selector.select(point);
+            Consumer expected = selectedConsumersBeforeRemove.get(j);
+            assertThat(selected.consumerId()).as("validationPoint %d, hash %d", j, point).isEqualTo(expected.consumerId());
+        }
+    }
+
+    private List<Integer> pointsToTest(int validationPointCount) {
+        List<Integer> res = new ArrayList<>();
+        int hashRangeSize = Integer.MAX_VALUE;
+        final int increment = hashRangeSize / (validationPointCount + 1);
+        for (int i = 0; i < validationPointCount; i++) {
+            res.add(i * increment);
+        }
+        return res;
     }
 }
diff --git a/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/ConsumerIdentityWrapperTest.java b/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/ConsumerIdentityWrapperTest.java
new file mode 100644
index 00000000000..75c8e6db5d2
--- /dev/null
+++ b/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/ConsumerIdentityWrapperTest.java
@@ -0,0 +1,68 @@
+/*
+ * 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.pulsar.broker.service;
+
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+import static org.testng.Assert.assertEquals;
+import static org.testng.Assert.assertNotEquals;
+import org.testng.annotations.Test;
+
+@Test(groups = "broker")
+public class ConsumerIdentityWrapperTest {
+    private static Consumer mockConsumer() {
+        return mockConsumer("consumer");
+    }
+
+    private static Consumer mockConsumer(String consumerName) {
+        Consumer consumer = mock(Consumer.class);
+        when(consumer.consumerName()).thenReturn(consumerName);
+        return consumer;
+    }
+
+    @Test
+    public void testEquals() {
+        Consumer consumer = mockConsumer();
+        assertEquals(new ConsumerIdentityWrapper(consumer), new ConsumerIdentityWrapper(consumer));
+    }
+
+    @Test
+    public void testHashCode() {
+        Consumer consumer = mockConsumer();
+        assertEquals(new ConsumerIdentityWrapper(consumer).hashCode(),
+                new ConsumerIdentityWrapper(consumer).hashCode());
+    }
+
+    @Test
+    public void testEqualsAndHashCode() {
+        Consumer consumer1 = mockConsumer();
+        Consumer consumer2 = mockConsumer();
+        ConsumerIdentityWrapper wrapper1 = new ConsumerIdentityWrapper(consumer1);
+        ConsumerIdentityWrapper wrapper2 = new ConsumerIdentityWrapper(consumer1);
+        ConsumerIdentityWrapper wrapper3 = new ConsumerIdentityWrapper(consumer2);
+
+        // Test equality
+        assertEquals(wrapper1, wrapper2);
+        assertNotEquals(wrapper1, wrapper3);
+
+        // Test hash code
+        assertEquals(wrapper1.hashCode(), wrapper2.hashCode());
+        assertNotEquals(wrapper1.hashCode(), wrapper3.hashCode());
+    }
+}
\ No newline at end of file
diff --git a/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/ConsumerNameIndexTrackerTest.java b/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/ConsumerNameIndexTrackerTest.java
new file mode 100644
index 00000000000..0f18ecce2ff
--- /dev/null
+++ b/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/ConsumerNameIndexTrackerTest.java
@@ -0,0 +1,157 @@
+/*
+ * 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.pulsar.broker.service;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+import static org.testng.Assert.assertEquals;
+import static org.testng.Assert.assertNotEquals;
+import java.util.List;
+import java.util.Map;
+import java.util.stream.Collectors;
+import java.util.stream.IntStream;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+
+@Test(groups = "broker")
+public class ConsumerNameIndexTrackerTest {
+    private ConsumerNameIndexTracker tracker;
+
+    @BeforeMethod
+    public void setUp() {
+        tracker = new ConsumerNameIndexTracker();
+    }
+
+    private static Consumer mockConsumer() {
+        return mockConsumer("consumer");
+    }
+
+
+    private static Consumer mockConsumer(String consumerName) {
+        Consumer consumer = mock(Consumer.class);
+        when(consumer.consumerName()).thenReturn(consumerName);
+        return consumer;
+    }
+
+    @Test
+    public void testIncreaseConsumerRefCountAndReturnIndex() {
+        Consumer consumer1 = mockConsumer();
+        Consumer consumer2 = mockConsumer();
+        ConsumerIdentityWrapper wrapper1 = new ConsumerIdentityWrapper(consumer1);
+        ConsumerIdentityWrapper wrapper2 = new ConsumerIdentityWrapper(consumer2);
+        int index1 = tracker.increaseConsumerRefCountAndReturnIndex(wrapper1);
+        int index2 = tracker.increaseConsumerRefCountAndReturnIndex(wrapper2);
+        assertNotEquals(index1, index2);
+        assertEquals(index1, tracker.getTrackedIndex(wrapper1));
+        assertEquals(index2, tracker.getTrackedIndex(wrapper2));
+    }
+
+    @Test
+    public void testTrackingReturnsStableIndexWhenRemovedAndAddedInSameOrder() {
+        List<ConsumerIdentityWrapper> consumerIdentityWrappers =
+                IntStream.range(0, 100).mapToObj(i -> mockConsumer()).map(ConsumerIdentityWrapper::new).toList();
+        Map<ConsumerIdentityWrapper, Integer> trackedIndexes =
+                consumerIdentityWrappers.stream().collect(Collectors.toMap(
+                        wrapper -> wrapper, wrapper -> tracker.increaseConsumerRefCountAndReturnIndex(wrapper)));
+        // stop tracking every other consumer
+        for (int i = 0; i < consumerIdentityWrappers.size(); i++) {
+            if (i % 2 == 0) {
+                tracker.decreaseConsumerRefCount(consumerIdentityWrappers.get(i));
+            }
+        }
+        // check that others are tracked
+        for (int i = 0; i < consumerIdentityWrappers.size(); i++) {
+            ConsumerIdentityWrapper wrapper = consumerIdentityWrappers.get(i);
+            int trackedIndex = tracker.getTrackedIndex(wrapper);
+            assertEquals(trackedIndex, i % 2 == 0 ? -1 : trackedIndexes.get(wrapper));
+        }
+        // check that new consumers are tracked with the same index
+        for (int i = 0; i < consumerIdentityWrappers.size(); i++) {
+            ConsumerIdentityWrapper wrapper = consumerIdentityWrappers.get(i);
+            if (i % 2 == 0) {
+                int trackedIndex = tracker.increaseConsumerRefCountAndReturnIndex(wrapper);
+                assertEquals(trackedIndex, trackedIndexes.get(wrapper));
+            }
+        }
+        // check that all consumers are tracked with the original indexes
+        for (int i = 0; i < consumerIdentityWrappers.size(); i++) {
+            ConsumerIdentityWrapper wrapper = consumerIdentityWrappers.get(i);
+            int trackedIndex = tracker.getTrackedIndex(wrapper);
+            assertEquals(trackedIndex, trackedIndexes.get(wrapper));
+        }
+    }
+
+    @Test
+    public void testTrackingMultipleTimes() {
+        List<ConsumerIdentityWrapper> consumerIdentityWrappers =
+                IntStream.range(0, 100).mapToObj(i -> mockConsumer()).map(ConsumerIdentityWrapper::new).toList();
+        Map<ConsumerIdentityWrapper, Integer> trackedIndexes =
+                consumerIdentityWrappers.stream().collect(Collectors.toMap(
+                        wrapper -> wrapper, wrapper -> tracker.increaseConsumerRefCountAndReturnIndex(wrapper)));
+        Map<ConsumerIdentityWrapper, Integer> trackedIndexes2 =
+                consumerIdentityWrappers.stream().collect(Collectors.toMap(
+                        wrapper -> wrapper, wrapper -> tracker.increaseConsumerRefCountAndReturnIndex(wrapper)));
+        assertThat(tracker.getTrackedConsumerNamesCount()).isEqualTo(1);
+        assertThat(trackedIndexes).containsExactlyInAnyOrderEntriesOf(trackedIndexes2);
+        consumerIdentityWrappers.forEach(wrapper -> tracker.decreaseConsumerRefCount(wrapper));
+        for (ConsumerIdentityWrapper wrapper : consumerIdentityWrappers) {
+            int trackedIndex = tracker.getTrackedIndex(wrapper);
+            assertEquals(trackedIndex, trackedIndexes.get(wrapper));
+        }
+        consumerIdentityWrappers.forEach(wrapper -> tracker.decreaseConsumerRefCount(wrapper));
+        assertThat(tracker.getTrackedConsumersCount()).isEqualTo(0);
+        assertThat(tracker.getTrackedConsumerNamesCount()).isEqualTo(0);
+    }
+
+    @Test
+    public void testDecreaseConsumerRefCount() {
+        Consumer consumer1 = mockConsumer();
+        ConsumerIdentityWrapper wrapper1 = new ConsumerIdentityWrapper(consumer1);
+        int index1 = tracker.increaseConsumerRefCountAndReturnIndex(wrapper1);
+        assertNotEquals(index1, -1);
+        tracker.decreaseConsumerRefCount(wrapper1);
+        assertEquals(tracker.getTrackedIndex(wrapper1), -1);
+    }
+
+    @Test
+    public void testGetTrackedIndex() {
+        Consumer consumer1 = mockConsumer();
+        Consumer consumer2 = mockConsumer();
+        ConsumerIdentityWrapper wrapper1 = new ConsumerIdentityWrapper(consumer1);
+        ConsumerIdentityWrapper wrapper2 = new ConsumerIdentityWrapper(consumer2);
+        int index1 = tracker.increaseConsumerRefCountAndReturnIndex(wrapper1);
+        int index2 = tracker.increaseConsumerRefCountAndReturnIndex(wrapper2);
+        assertEquals(index1, tracker.getTrackedIndex(wrapper1));
+        assertEquals(index2, tracker.getTrackedIndex(wrapper2));
+    }
+
+    @Test
+    public void testTrackingMultipleNames() {
+        List<ConsumerIdentityWrapper> consumerIdentityWrappers =
+                IntStream.range(0, 100).mapToObj(i -> mockConsumer("consumer" + i)).map(ConsumerIdentityWrapper::new)
+                        .toList();
+        consumerIdentityWrappers.forEach(wrapper -> tracker.increaseConsumerRefCountAndReturnIndex(wrapper));
+        assertThat(tracker.getTrackedConsumerNamesCount()).isEqualTo(100);
+        assertThat(tracker.getTrackedConsumersCount()).isEqualTo(100);
+        consumerIdentityWrappers.forEach(wrapper -> tracker.decreaseConsumerRefCount(wrapper));
+        assertThat(tracker.getTrackedConsumersCount()).isEqualTo(0);
+        assertThat(tracker.getTrackedConsumerNamesCount()).isEqualTo(0);
+    }
+}
\ No newline at end of file
diff --git a/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/persistent/PersistentStickyKeyDispatcherMultipleConsumersTest.java b/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/persistent/PersistentStickyKeyDispatcherMultipleConsumersTest.java
index 03eb01e958a..3fe3fef3299 100644
--- a/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/persistent/PersistentStickyKeyDispatcherMultipleConsumersTest.java
+++ b/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/persistent/PersistentStickyKeyDispatcherMultipleConsumersTest.java
@@ -20,6 +20,7 @@ package org.apache.pulsar.broker.service.persistent;
 
 import static java.nio.charset.StandardCharsets.UTF_8;
 import static org.apache.pulsar.common.protocol.Commands.serializeMetadataAndPayload;
+import static org.assertj.core.api.Assertions.assertThat;
 import static org.mockito.Mockito.any;
 import static org.mockito.Mockito.anyBoolean;
 import static org.mockito.Mockito.anyInt;
@@ -262,7 +263,7 @@ public class PersistentStickyKeyDispatcherMultipleConsumersTest {
         redeliverEntries.add(EntryImpl.create(1, 1, createMessage("message1", 1, "key1")));
         final List<Entry> readEntries = new ArrayList<>();
         readEntries.add(EntryImpl.create(1, 2, createMessage("message2", 2, "key1")));
-        readEntries.add(EntryImpl.create(1, 3, createMessage("message3", 3, "key22")));
+        readEntries.add(EntryImpl.create(1, 3, createMessage("message3", 3, "key2")));
 
         try {
             Field totalAvailablePermitsField = PersistentDispatcherMultipleConsumers.class.getDeclaredField("totalAvailablePermits");
@@ -358,7 +359,7 @@ public class PersistentStickyKeyDispatcherMultipleConsumersTest {
 
         // Messages with key1 are routed to consumer1 and messages with key2 are routed to consumer2
         final List<Entry> allEntries = new ArrayList<>();
-        allEntries.add(EntryImpl.create(1, 1, createMessage("message1", 1, "key22")));
+        allEntries.add(EntryImpl.create(1, 1, createMessage("message1", 1, "key2")));
         allEntries.add(EntryImpl.create(1, 2, createMessage("message2", 2, "key1")));
         allEntries.add(EntryImpl.create(1, 3, createMessage("message3", 3, "key1")));
         allEntries.forEach(entry -> ((EntryImpl) entry).retain());
@@ -459,8 +460,8 @@ public class PersistentStickyKeyDispatcherMultipleConsumersTest {
             persistentDispatcher.readMoreEntries();
         }
 
-        assertEquals(actualEntriesToConsumer1, expectedEntriesToConsumer1);
-        assertEquals(actualEntriesToConsumer2, expectedEntriesToConsumer2);
+        assertThat(actualEntriesToConsumer1).containsExactlyElementsOf(expectedEntriesToConsumer1);
+        assertThat(actualEntriesToConsumer2).containsExactlyElementsOf(expectedEntriesToConsumer2);
 
         allEntries.forEach(entry -> entry.release());
     }
diff --git a/pulsar-client-api/src/main/java/org/apache/pulsar/client/api/Range.java b/pulsar-client-api/src/main/java/org/apache/pulsar/client/api/Range.java
index 4437ffc4ac6..488083f484b 100644
--- a/pulsar-client-api/src/main/java/org/apache/pulsar/client/api/Range.java
+++ b/pulsar-client-api/src/main/java/org/apache/pulsar/client/api/Range.java
@@ -27,7 +27,7 @@ import org.apache.pulsar.common.classification.InterfaceStability;
  */
 @InterfaceAudience.Public
 @InterfaceStability.Stable
-public class Range {
+public class Range implements Comparable<Range> {
 
     private final int start;
     private final int end;
@@ -84,4 +84,13 @@ public class Range {
     public String toString() {
         return "[" + start + ", " + end + "]";
     }
+
+    @Override
+    public int compareTo(Range o) {
+        int result = Integer.compare(start, o.start);
+        if (result == 0) {
+            result = Integer.compare(end, o.end);
+        }
+        return result;
+    }
 }


(pulsar) 05/09: [improve][build] Use amazoncorretto:21-alpine image instead of apk installation (#22973)

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

lhotari pushed a commit to branch branch-3.3
in repository https://gitbox.apache.org/repos/asf/pulsar.git

commit 8b47a528dedaf0ae65b3a5f20305667341980e95
Author: Zixuan Liu <no...@gmail.com>
AuthorDate: Tue Jun 25 18:04:02 2024 +0800

    [improve][build] Use amazoncorretto:21-alpine image instead of apk installation (#22973)
    
    Signed-off-by: Zixuan Liu <no...@gmail.com>
    (cherry picked from commit 7dba98bed46231ce9bd2bd2d8f5369b50a2119be)
---
 docker/pulsar/Dockerfile | 6 ++----
 1 file changed, 2 insertions(+), 4 deletions(-)

diff --git a/docker/pulsar/Dockerfile b/docker/pulsar/Dockerfile
index 2957e1587e9..38b74e8503d 100644
--- a/docker/pulsar/Dockerfile
+++ b/docker/pulsar/Dockerfile
@@ -54,11 +54,9 @@ RUN chmod -R o+rx /pulsar
 RUN echo 'OPTS="$OPTS -Dorg.xerial.snappy.use.systemlib=true"' >> /pulsar/conf/bkenv.sh
 
 ###  Create one stage to include JVM distribution
-FROM alpine:$ALPINE_VERSION AS jvm
+FROM amazoncorretto:21-alpine AS jvm
 
-RUN wget -O /etc/apk/keys/amazoncorretto.rsa.pub https://apk.corretto.aws/amazoncorretto.rsa.pub
-RUN echo "https://apk.corretto.aws" >> /etc/apk/repositories
-RUN apk add --no-cache amazon-corretto-21 binutils
+RUN apk add --no-cache binutils
 
 # Use JLink to create a slimmer JDK distribution (see: https://adoptium.net/blog/2021/10/jlink-to-produce-own-runtime/)
 # This still includes all JDK modules, though in the future we could compile a list of required modules