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 2025/04/25 15:08:30 UTC

(pulsar) branch branch-3.0 updated (d1bb49c8e48 -> 81cf17da34a)

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

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


    from d1bb49c8e48 [fix][admin] Backlog quota's policy is null which causes a NPE (#24192)
     new 0d5baa52024 [fix][broker] Fix tenant creation and update with null value (#24209)
     new 81cf17da34a [fix][broker] Fix HealthChecker deadlock in shutdown (#24216)

The 2 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:
 .../pulsar/broker/admin/impl/TenantsBase.java      |  24 +++--
 .../pulsar/broker/service/HealthChecker.java       | 109 ++++++++++++++-------
 .../pulsar/broker/admin/AdminApiTenantTest.java    |  46 +++++++++
 3 files changed, 134 insertions(+), 45 deletions(-)


(pulsar) 02/02: [fix][broker] Fix HealthChecker deadlock in shutdown (#24216)

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.0
in repository https://gitbox.apache.org/repos/asf/pulsar.git

commit 81cf17da34a940c71b436acee708f2acb97e20ae
Author: Lari Hotari <lh...@users.noreply.github.com>
AuthorDate: Fri Apr 25 18:00:56 2025 +0300

    [fix][broker] Fix HealthChecker deadlock in shutdown (#24216)
    
    (cherry picked from commit 279e33d9531ab2ec4a53732670110e93a93e18b1)
---
 .../pulsar/broker/service/HealthChecker.java       | 109 ++++++++++++++-------
 1 file changed, 71 insertions(+), 38 deletions(-)

diff --git a/pulsar-broker/src/main/java/org/apache/pulsar/broker/service/HealthChecker.java b/pulsar-broker/src/main/java/org/apache/pulsar/broker/service/HealthChecker.java
index e80e0b09475..1df828e2c95 100644
--- a/pulsar-broker/src/main/java/org/apache/pulsar/broker/service/HealthChecker.java
+++ b/pulsar-broker/src/main/java/org/apache/pulsar/broker/service/HealthChecker.java
@@ -18,9 +18,10 @@
  */
 package org.apache.pulsar.broker.service;
 
+import com.google.common.util.concurrent.MoreExecutors;
+import io.netty.util.concurrent.DefaultThreadFactory;
 import java.time.Duration;
 import java.util.ArrayList;
-import java.util.Collections;
 import java.util.HashSet;
 import java.util.List;
 import java.util.Objects;
@@ -28,6 +29,9 @@ import java.util.Optional;
 import java.util.Set;
 import java.util.UUID;
 import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.Executors;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.TimeUnit;
 import java.util.concurrent.TimeoutException;
 import lombok.extern.slf4j.Slf4j;
 import org.apache.bookkeeper.mledger.ManagedLedgerException;
@@ -51,6 +55,7 @@ import org.apache.pulsar.metadata.api.MetadataStoreException;
  * The HealthChecker class provides functionality to monitor and verify the health of a Pulsar broker.
  * It performs health checks by creating test topics, producing and consuming messages to verify broker functionality.
  * This class implements AutoCloseable to ensure proper cleanup of resources when the broker is shut down.
+ * Tests are in AdminApiHealthCheckTest class.
  */
 @Slf4j
 public class HealthChecker implements AutoCloseable{
@@ -102,6 +107,11 @@ public class HealthChecker implements AutoCloseable{
      */
     private final Set<CompletableFuture<Void>> pendingFutures = new HashSet<>();
 
+    /**
+     * Executor for health check operations.
+     */
+    private final ScheduledExecutorService healthCheckExecutor;
+
     private final Duration timeout = DEFAULT_HEALTH_CHECK_READ_TIMEOUT;
 
     public HealthChecker(PulsarService pulsar) throws PulsarServerException {
@@ -112,6 +122,8 @@ public class HealthChecker implements AutoCloseable{
                 new ScheduledExecutorProvider(1, "health-checker-client-lookup-executor");
         this.scheduledExecutorProvider =
                 new ScheduledExecutorProvider(1, "health-checker-client-scheduled-executor");
+        this.healthCheckExecutor =
+                Executors.newSingleThreadScheduledExecutor(new DefaultThreadFactory("health-checker-executor"));
         try {
             this.client = pulsar.createClientImpl(builder -> {
                 builder.lookupExecutorProvider(lookupExecutor);
@@ -145,15 +157,22 @@ public class HealthChecker implements AutoCloseable{
         log.info("[{}] Running healthCheck with topic={}", clientAppId, topicName);
         final String messageStr = UUID.randomUUID().toString();
         final String subscriptionName = "healthCheck-" + messageStr;
-        // create non-partitioned topic manually and close the previous reader if present.
+
         CompletableFuture<Void> resultFuture = new CompletableFuture<>();
+        healthCheckExecutor.execute(
+                () -> doHealthCheck(clientAppId, resultFuture, topicName, subscriptionName, messageStr));
+        return resultFuture;
+    }
+
+    private void doHealthCheck(String clientAppId, CompletableFuture<Void> resultFuture, String topicName,
+                           String subscriptionName, String messageStr) {
         addToPending(resultFuture);
-        resultFuture.whenComplete((result, ex) -> {
+        resultFuture.whenCompleteAsync((result, ex) -> {
             removeFromPending(resultFuture);
-        });
+        }, healthCheckExecutor);
         try {
             pulsar.getBrokerService().getTopic(topicName, true)
-                    .thenCompose(topicOptional -> {
+                    .thenComposeAsync(topicOptional -> {
                         if (!topicOptional.isPresent()) {
                             log.error("[{}] Fail to run health check while get topic {}. because get null value.",
                                     clientAppId, topicName);
@@ -161,7 +180,7 @@ public class HealthChecker implements AutoCloseable{
                                     String.format("Topic [%s] not found after create.", topicName)));
                         }
                         return doHealthCheck(clientAppId, topicName, subscriptionName, messageStr, resultFuture);
-                    }).whenComplete((result, t) -> {
+                    }, healthCheckExecutor).whenComplete((result, t) -> {
                         if (t != null) {
                             resultFuture.completeExceptionally(t);
                         } else {
@@ -175,7 +194,6 @@ public class HealthChecker implements AutoCloseable{
                     clientAppId, topicName, e);
             resultFuture.completeExceptionally(e);
         }
-        return resultFuture;
     }
 
     private synchronized void addToPending(CompletableFuture<Void> resultFuture) {
@@ -188,34 +206,38 @@ public class HealthChecker implements AutoCloseable{
 
     private CompletableFuture<Void> doHealthCheck(String clientAppId, String topicName, String subscriptionName,
                                                   String messageStr, CompletableFuture<Void> resultFuture) {
-        return client.newProducer(Schema.STRING).topic(topicName).createAsync()
-                .thenCompose(producer -> client.newReader(Schema.STRING).topic(topicName)
+        return client.newProducer(Schema.STRING)
+                .topic(topicName)
+                .sendTimeout((int) timeout.toMillis(), TimeUnit.MILLISECONDS)
+                .enableBatching(false)
+                .createAsync()
+                .thenCompose(producer -> client.newReader(Schema.STRING)
+                        .topic(topicName)
                         .subscriptionName(subscriptionName)
                         .startMessageId(MessageId.latest)
-                        .createAsync().exceptionally(createException -> {
+                        .createAsync()
+                        .exceptionally(createException -> {
                             producer.closeAsync().exceptionally(ex -> {
                                 log.error("[{}] Close producer fail while heath check.", clientAppId);
                                 return null;
                             });
                             throw FutureUtil.wrapToCompletionException(createException);
-                        }).thenCompose(reader -> producer.sendAsync(messageStr)
+                        })
+                        .thenCompose(reader -> producer.sendAsync(messageStr)
                                 .thenCompose(__ -> FutureUtil.addTimeoutHandling(
                                         healthCheckRecursiveReadNext(reader, messageStr),
-                                        timeout, pulsar.getBrokerService().executor(),
+                                        timeout, healthCheckExecutor,
                                         () -> HEALTH_CHECK_TIMEOUT_EXCEPTION))
-                                .whenComplete((__, ex) -> {
-                                            closeAndReCheck(producer, reader, topicName,
-                                                    subscriptionName,
-                                                    clientAppId)
-                                                    .whenComplete((unused, innerEx) -> {
-                                                        if (ex != null) {
-                                                            resultFuture.completeExceptionally(ex);
-                                                        } else {
-                                                            resultFuture.complete(null);
-                                                        }
-                                                    });
-                                        }
-                                ))
+                                .whenCompleteAsync((__, ex) -> {
+                                    closeAndReCheck(producer, reader, topicName, subscriptionName, clientAppId)
+                                            .whenComplete((unused, innerEx) -> {
+                                                if (ex != null) {
+                                                    resultFuture.completeExceptionally(ex);
+                                                } else {
+                                                    resultFuture.complete(null);
+                                                }
+                                            });
+                                }, healthCheckExecutor))
                 ).exceptionally(ex -> {
                     resultFuture.completeExceptionally(ex);
                     return null;
@@ -237,14 +259,14 @@ public class HealthChecker implements AutoCloseable{
                                                     String topicName, String subscriptionName, String clientAppId) {
         // no matter exception or success, we still need to
         // close producer/reader
-        CompletableFuture<Void> producerFuture = producer.closeAsync();
-        CompletableFuture<Void> readerFuture = reader.closeAsync();
+        CompletableFuture<Void> producerCloseFuture = producer.closeAsync();
+        CompletableFuture<Void> readerCloseFuture = reader.closeAsync();
         List<CompletableFuture<Void>> futures = new ArrayList<>(2);
-        futures.add(producerFuture);
-        futures.add(readerFuture);
-        return FutureUtil.waitForAll(Collections.unmodifiableList(futures))
-                .exceptionally(closeException -> {
-                    if (readerFuture.isCompletedExceptionally()) {
+        futures.add(producerCloseFuture);
+        futures.add(readerCloseFuture);
+        return FutureUtil.waitForAll(futures)
+                .exceptionallyAsync(closeException -> {
+                    if (readerCloseFuture.isCompletedExceptionally()) {
                         log.error("[{}] Close reader fail while health check.", clientAppId);
                         Optional<Topic> topic = pulsar.getBrokerService().getTopicReference(topicName);
                         if (topic.isPresent()) {
@@ -270,7 +292,7 @@ public class HealthChecker implements AutoCloseable{
                         log.error("[{}] Close producer fail while heath check.", clientAppId);
                     }
                     return null;
-                });
+                }, healthCheckExecutor);
     }
 
     private static CompletableFuture<Void> healthCheckRecursiveReadNext(Reader<String> reader, String content) {
@@ -290,14 +312,15 @@ public class HealthChecker implements AutoCloseable{
         log.info("finish forcefully deleting heartbeat topics");
     }
 
-    private void deleteTopic(String heartbeatTopicV1) {
+    private void deleteTopic(String topicName) {
         try {
-            pulsar.getBrokerService().deleteTopic(heartbeatTopicV1, true).get();
+            pulsar.getBrokerService().deleteTopic(topicName, true)
+                    .get(pulsar.getConfiguration().getMetadataStoreOperationTimeoutSeconds(), TimeUnit.SECONDS);
         } catch (Exception e) {
             Throwable realCause = e.getCause();
             if (!(realCause instanceof ManagedLedgerException.MetadataNotFoundException
                     || realCause instanceof MetadataStoreException.NotFoundException)) {
-                log.error("Errors in deleting heartbeat topic [{}]", heartbeatTopicV1, e);
+                log.error("Errors in deleting heartbeat topic [{}]", topicName, e);
             }
         }
     }
@@ -321,10 +344,20 @@ public class HealthChecker implements AutoCloseable{
         }
         for (CompletableFuture<Void> pendingFuture : new ArrayList<>(pendingFutures)) {
             if (!pendingFuture.isDone()) {
-                pendingFuture.completeExceptionally(
-                        new PulsarClientException.AlreadyClosedException("HealthChecker is closed"));
+                healthCheckExecutor.submit(() -> {
+                    try {
+                        pendingFuture.completeExceptionally(
+                                new PulsarClientException.AlreadyClosedException("HealthChecker is closed"));
+                    } catch (Exception e) {
+                        log.warn("Failed to complete pending future", e);
+                    }
+                });
             }
         }
+        boolean terminated = MoreExecutors.shutdownAndAwaitTermination(healthCheckExecutor, 10, TimeUnit.SECONDS);
+        if (!terminated) {
+            log.warn("Failed to shutdown health check executor in 10 seconds");
+        }
         deleteHeartbeatTopics();
     }
 }


(pulsar) 01/02: [fix][broker] Fix tenant creation and update with null value (#24209)

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.0
in repository https://gitbox.apache.org/repos/asf/pulsar.git

commit 0d5baa52024db9fbe7ab77d1643e72c5e2cdc239
Author: Zixuan Liu <no...@gmail.com>
AuthorDate: Fri Apr 25 22:34:22 2025 +0800

    [fix][broker] Fix tenant creation and update with null value (#24209)
    
    Signed-off-by: Zixuan Liu <no...@gmail.com>
    (cherry picked from commit c59412eba525ab460440215c78d7ab831b90111e)
---
 .../pulsar/broker/admin/impl/TenantsBase.java      | 24 +++++++----
 .../pulsar/broker/admin/AdminApiTenantTest.java    | 46 ++++++++++++++++++++++
 2 files changed, 63 insertions(+), 7 deletions(-)

diff --git a/pulsar-broker/src/main/java/org/apache/pulsar/broker/admin/impl/TenantsBase.java b/pulsar-broker/src/main/java/org/apache/pulsar/broker/admin/impl/TenantsBase.java
index cb60414edeb..eea0bcba0ab 100644
--- a/pulsar-broker/src/main/java/org/apache/pulsar/broker/admin/impl/TenantsBase.java
+++ b/pulsar-broker/src/main/java/org/apache/pulsar/broker/admin/impl/TenantsBase.java
@@ -270,15 +270,25 @@ public class TenantsBase extends PulsarWebResource {
     }
 
     private CompletableFuture<Void> validateClustersAsync(TenantInfo info) {
-        // empty cluster shouldn't be allowed
-        if (info == null || info.getAllowedClusters().stream().filter(c -> !StringUtils.isBlank(c))
-                .collect(Collectors.toSet()).isEmpty()
-                || info.getAllowedClusters().stream().anyMatch(ac -> StringUtils.isBlank(ac))) {
-            log.warn("[{}] Failed to validate due to clusters are empty", clientAppId());
-            return FutureUtil.failedFuture(new RestException(Status.PRECONDITION_FAILED, "Clusters can not be empty"));
+        if (info == null) {
+            return FutureUtil.failedFuture(new RestException(Status.PRECONDITION_FAILED, "TenantInfo is null"));
         }
+
+        Set<String> allowedClusters = info.getAllowedClusters();
+        if (allowedClusters == null) {
+            return FutureUtil.failedFuture(new RestException(Status.PRECONDITION_FAILED, "Clusters cannot be null"));
+        }
+
+        Set<String> cleanedClusters = allowedClusters.stream()
+                .filter(c -> !StringUtils.isBlank(c))
+                .collect(Collectors.toSet());
+        if (cleanedClusters.isEmpty() || allowedClusters.stream().anyMatch(StringUtils::isBlank)) {
+            log.warn("[{}] Validation failed: allowed clusters are empty or contain blanks", clientAppId());
+            return FutureUtil.failedFuture(
+                    new RestException(Status.PRECONDITION_FAILED, "Clusters cannot be empty or blank"));
+        }
+
         return clusterResources().listAsync().thenAccept(availableClusters -> {
-            Set<String> allowedClusters = info.getAllowedClusters();
             List<String> nonexistentClusters = allowedClusters.stream()
                     .filter(cluster -> !(availableClusters.contains(cluster) || GLOBAL_CLUSTER.equals(cluster)))
                     .collect(Collectors.toList());
diff --git a/pulsar-broker/src/test/java/org/apache/pulsar/broker/admin/AdminApiTenantTest.java b/pulsar-broker/src/test/java/org/apache/pulsar/broker/admin/AdminApiTenantTest.java
index f8834176142..26a645d37e5 100644
--- a/pulsar-broker/src/test/java/org/apache/pulsar/broker/admin/AdminApiTenantTest.java
+++ b/pulsar-broker/src/test/java/org/apache/pulsar/broker/admin/AdminApiTenantTest.java
@@ -30,6 +30,7 @@ import org.apache.pulsar.broker.auth.MockedPulsarServiceBaseTest;
 import org.apache.pulsar.client.admin.PulsarAdminException;
 import org.apache.pulsar.common.policies.data.ClusterData;
 import org.apache.pulsar.common.policies.data.TenantInfo;
+import org.apache.pulsar.common.policies.data.TenantInfoImpl;
 import org.testng.annotations.BeforeClass;
 import org.testng.annotations.Test;
 
@@ -73,4 +74,49 @@ public class AdminApiTenantTest extends MockedPulsarServiceBaseTest {
         String tenant = "test-non-exist-tenant-" + UUID.randomUUID();
         assertThrows(PulsarAdminException.NotFoundException.class, () -> admin.tenants().deleteTenant(tenant));
     }
+
+    @Test
+    public void testCreateTenantWithNull() {
+        String tenant = "test-create-tenant-with-null-value-" + UUID.randomUUID();
+        // Put doesn't allow null value
+        assertThrows(PulsarAdminException.class,
+                () -> admin.tenants().createTenant(tenant, null));
+    }
+
+    @Test
+    public void testCreateTenantWithInvalidCluster() {
+        String tenant = "test-create-tenant-with-invalid-cluster-" + UUID.randomUUID();
+        // clusters is empty
+        assertThrows(PulsarAdminException.PreconditionFailedException.class,
+                () -> admin.tenants().createTenant(tenant, TenantInfo.builder().build()));
+
+        // clusters is null
+        assertThrows(PulsarAdminException.PreconditionFailedException.class,
+                () -> {
+                    TenantInfoImpl tenantInfo = new TenantInfoImpl();
+                    tenantInfo.setAdminRoles(null);
+                    tenantInfo.setAllowedClusters(null);
+                    admin.tenants().createTenant(tenant, tenantInfo);
+                });
+    }
+
+    @Test
+    public void testUpdateTenantWithInvalidCluster() throws PulsarAdminException {
+        String tenant = "test-update-tenant-with-invalid-cluster-" + UUID.randomUUID();
+        admin.tenants().createTenant(tenant,
+                TenantInfo.builder().allowedClusters(Collections.singleton(CLUSTER)).build());
+
+        // clusters is empty
+        assertThrows(PulsarAdminException.PreconditionFailedException.class,
+                () -> admin.tenants().updateTenant(tenant, TenantInfo.builder().build()));
+
+        // clusters is null
+        assertThrows(PulsarAdminException.PreconditionFailedException.class,
+                () -> {
+                    TenantInfoImpl tenantInfo = new TenantInfoImpl();
+                    tenantInfo.setAdminRoles(null);
+                    tenantInfo.setAllowedClusters(null);
+                    admin.tenants().updateTenant(tenant, tenantInfo);
+                });
+    }
 }