heesung-sn commented on code in PR #18810:
URL: https://github.com/apache/pulsar/pull/18810#discussion_r1045513312


##########
pulsar-broker/src/main/java/org/apache/pulsar/broker/loadbalance/extensions/BrokerRegistryImpl.java:
##########
@@ -0,0 +1,218 @@
+/*
+ * 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 com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.Lists;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.CompletionException;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.RejectedExecutionException;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.function.BiConsumer;
+import lombok.extern.slf4j.Slf4j;
+import org.apache.pulsar.broker.PulsarServerException;
+import org.apache.pulsar.broker.PulsarService;
+import org.apache.pulsar.broker.ServiceConfiguration;
+import org.apache.pulsar.broker.loadbalance.extensions.data.BrokerLookupData;
+import org.apache.pulsar.common.util.FutureUtil;
+import org.apache.pulsar.metadata.api.MetadataStoreException;
+import org.apache.pulsar.metadata.api.Notification;
+import org.apache.pulsar.metadata.api.NotificationType;
+import org.apache.pulsar.metadata.api.coordination.LockManager;
+import org.apache.pulsar.metadata.api.coordination.ResourceLock;
+
+/**
+ * The broker registry impl, base on the LockManager.
+ */
+@Slf4j
+public class BrokerRegistryImpl implements BrokerRegistry {
+
+    private static final String LOOKUP_DATA_PATH = "/loadbalance/brokers";
+
+    private final PulsarService pulsar;
+
+    private final ServiceConfiguration conf;
+
+    private final BrokerLookupData brokerLookupData;
+
+    private final LockManager<BrokerLookupData> brokerLookupDataLockManager;
+
+    private final String brokerZNodePath;
+
+    private final String lookupServiceAddress;
+
+    @VisibleForTesting
+    protected final Map<String, BrokerLookupData> brokerLookupDataMap;
+
+    private final ScheduledExecutorService scheduler;
+
+    private final List<BiConsumer<String, NotificationType>> listeners;
+
+    private final AtomicBoolean registered;
+
+    private volatile ResourceLock<BrokerLookupData> brokerLookupDataLock;
+
+    public BrokerRegistryImpl(PulsarService pulsar) {
+        this.pulsar = pulsar;
+        this.conf = pulsar.getConfiguration();
+        this.brokerLookupDataLockManager = 
pulsar.getCoordinationService().getLockManager(BrokerLookupData.class);
+        this.scheduler = pulsar.getLoadManagerExecutor();
+        this.brokerLookupDataMap = new ConcurrentHashMap<>();
+        this.listeners = new ArrayList<>();
+
+        this.registered = new AtomicBoolean(false);
+        this.lookupServiceAddress = pulsar.getAdvertisedAddress() + ":"
+                + conf.getWebServicePort().orElseGet(() -> 
conf.getWebServicePortTls().get());
+        this.brokerZNodePath = LOOKUP_DATA_PATH + "/" + lookupServiceAddress;
+        this.brokerLookupData = new BrokerLookupData(
+                pulsar.getSafeWebServiceAddress(),
+                pulsar.getWebServiceAddressTls(),
+                pulsar.getBrokerServiceUrl(),
+                pulsar.getBrokerServiceUrlTls(),
+                pulsar.getAdvertisedListeners(),
+                pulsar.getProtocolDataToAdvertise(),
+                pulsar.getConfiguration().isEnablePersistentTopics(),
+                pulsar.getConfiguration().isEnableNonPersistentTopics(),
+                pulsar.getBrokerVersion());
+    }
+
+    @Override
+    public void start() {
+        
pulsar.getLocalMetadataStore().registerListener(this::handleMetadataStoreNotification);
+    }
+
+    @Override
+    public void register() {
+        if (registered.compareAndSet(false, true)) {
+            this.brokerLookupDataLock =
+                    brokerLookupDataLockManager.acquireLock(brokerZNodePath, 
brokerLookupData).join();
+        }
+    }
+
+    @Override
+    public void unregister() throws MetadataStoreException {
+        if (registered.compareAndSet(true, false)) {
+            try {
+                brokerLookupDataLock.release().join();
+            } catch (CompletionException e) {
+                throw MetadataStoreException.unwrap(e);
+            }
+        }
+    }
+
+    @Override
+    public String getLookupServiceAddress() {
+        return this.lookupServiceAddress;
+    }
+
+    @Override
+    public CompletableFuture<List<String>> getAvailableBrokersAsync() {
+        CompletableFuture<List<String>> future = new CompletableFuture<>();
+        brokerLookupDataLockManager.listLocks(LOOKUP_DATA_PATH)

Review Comment:
   Can we just return the cached list, 
`future.complete(Lists.newArrayList(this.brokerLookupDataMap.keySet()));`?
   Why do we need to use 
`brokerLookupDataLockManager.listLocks(LOOKUP_DATA_PATH)` every time?
   
   If this `listLocks` is for a more consistent `getAvailableBrokers` read, 
then why do we cache the broker list in `brokerLookupDataMap` and update the 
entries via the `zk listener`?
   
   Do we need to update the brokerLookupDataMap cache if the return list 
differs from brokerLookupDataMap.keySet() ?
   
   



##########
pulsar-broker/src/main/java/org/apache/pulsar/broker/loadbalance/extensions/BrokerRegistryImpl.java:
##########
@@ -0,0 +1,218 @@
+/*
+ * 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 com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.Lists;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.CompletionException;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.RejectedExecutionException;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.function.BiConsumer;
+import lombok.extern.slf4j.Slf4j;
+import org.apache.pulsar.broker.PulsarServerException;
+import org.apache.pulsar.broker.PulsarService;
+import org.apache.pulsar.broker.ServiceConfiguration;
+import org.apache.pulsar.broker.loadbalance.extensions.data.BrokerLookupData;
+import org.apache.pulsar.common.util.FutureUtil;
+import org.apache.pulsar.metadata.api.MetadataStoreException;
+import org.apache.pulsar.metadata.api.Notification;
+import org.apache.pulsar.metadata.api.NotificationType;
+import org.apache.pulsar.metadata.api.coordination.LockManager;
+import org.apache.pulsar.metadata.api.coordination.ResourceLock;
+
+/**
+ * The broker registry impl, base on the LockManager.
+ */
+@Slf4j
+public class BrokerRegistryImpl implements BrokerRegistry {
+
+    private static final String LOOKUP_DATA_PATH = "/loadbalance/brokers";
+
+    private final PulsarService pulsar;
+
+    private final ServiceConfiguration conf;
+
+    private final BrokerLookupData brokerLookupData;
+
+    private final LockManager<BrokerLookupData> brokerLookupDataLockManager;
+
+    private final String brokerZNodePath;
+
+    private final String lookupServiceAddress;
+
+    @VisibleForTesting
+    protected final Map<String, BrokerLookupData> brokerLookupDataMap;
+
+    private final ScheduledExecutorService scheduler;
+
+    private final List<BiConsumer<String, NotificationType>> listeners;
+
+    private final AtomicBoolean registered;
+
+    private volatile ResourceLock<BrokerLookupData> brokerLookupDataLock;
+
+    public BrokerRegistryImpl(PulsarService pulsar) {
+        this.pulsar = pulsar;
+        this.conf = pulsar.getConfiguration();
+        this.brokerLookupDataLockManager = 
pulsar.getCoordinationService().getLockManager(BrokerLookupData.class);
+        this.scheduler = pulsar.getLoadManagerExecutor();
+        this.brokerLookupDataMap = new ConcurrentHashMap<>();
+        this.listeners = new ArrayList<>();
+
+        this.registered = new AtomicBoolean(false);
+        this.lookupServiceAddress = pulsar.getAdvertisedAddress() + ":"
+                + conf.getWebServicePort().orElseGet(() -> 
conf.getWebServicePortTls().get());
+        this.brokerZNodePath = LOOKUP_DATA_PATH + "/" + lookupServiceAddress;
+        this.brokerLookupData = new BrokerLookupData(
+                pulsar.getSafeWebServiceAddress(),
+                pulsar.getWebServiceAddressTls(),
+                pulsar.getBrokerServiceUrl(),
+                pulsar.getBrokerServiceUrlTls(),
+                pulsar.getAdvertisedListeners(),
+                pulsar.getProtocolDataToAdvertise(),
+                pulsar.getConfiguration().isEnablePersistentTopics(),
+                pulsar.getConfiguration().isEnableNonPersistentTopics(),
+                pulsar.getBrokerVersion());
+    }
+
+    @Override
+    public void start() {
+        
pulsar.getLocalMetadataStore().registerListener(this::handleMetadataStoreNotification);
+    }
+
+    @Override
+    public void register() {
+        if (registered.compareAndSet(false, true)) {
+            this.brokerLookupDataLock =
+                    brokerLookupDataLockManager.acquireLock(brokerZNodePath, 
brokerLookupData).join();
+        }
+    }
+
+    @Override
+    public void unregister() throws MetadataStoreException {
+        if (registered.compareAndSet(true, false)) {

Review Comment:
   what if `brokerLookupDataLock.release(..)` fails (but we pre-set 
`registered` to false in this case)?



##########
pulsar-broker/src/main/java/org/apache/pulsar/broker/loadbalance/extensions/BrokerRegistryImpl.java:
##########
@@ -0,0 +1,218 @@
+/*
+ * 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 com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.Lists;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.CompletionException;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.RejectedExecutionException;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.function.BiConsumer;
+import lombok.extern.slf4j.Slf4j;
+import org.apache.pulsar.broker.PulsarServerException;
+import org.apache.pulsar.broker.PulsarService;
+import org.apache.pulsar.broker.ServiceConfiguration;
+import org.apache.pulsar.broker.loadbalance.extensions.data.BrokerLookupData;
+import org.apache.pulsar.common.util.FutureUtil;
+import org.apache.pulsar.metadata.api.MetadataStoreException;
+import org.apache.pulsar.metadata.api.Notification;
+import org.apache.pulsar.metadata.api.NotificationType;
+import org.apache.pulsar.metadata.api.coordination.LockManager;
+import org.apache.pulsar.metadata.api.coordination.ResourceLock;
+
+/**
+ * The broker registry impl, base on the LockManager.
+ */
+@Slf4j
+public class BrokerRegistryImpl implements BrokerRegistry {
+
+    private static final String LOOKUP_DATA_PATH = "/loadbalance/brokers";
+
+    private final PulsarService pulsar;
+
+    private final ServiceConfiguration conf;
+
+    private final BrokerLookupData brokerLookupData;
+
+    private final LockManager<BrokerLookupData> brokerLookupDataLockManager;
+
+    private final String brokerZNodePath;
+
+    private final String lookupServiceAddress;
+
+    @VisibleForTesting
+    protected final Map<String, BrokerLookupData> brokerLookupDataMap;
+
+    private final ScheduledExecutorService scheduler;
+
+    private final List<BiConsumer<String, NotificationType>> listeners;
+
+    private final AtomicBoolean registered;
+
+    private volatile ResourceLock<BrokerLookupData> brokerLookupDataLock;
+
+    public BrokerRegistryImpl(PulsarService pulsar) {
+        this.pulsar = pulsar;
+        this.conf = pulsar.getConfiguration();
+        this.brokerLookupDataLockManager = 
pulsar.getCoordinationService().getLockManager(BrokerLookupData.class);
+        this.scheduler = pulsar.getLoadManagerExecutor();
+        this.brokerLookupDataMap = new ConcurrentHashMap<>();
+        this.listeners = new ArrayList<>();
+
+        this.registered = new AtomicBoolean(false);
+        this.lookupServiceAddress = pulsar.getAdvertisedAddress() + ":"

Review Comment:
   can't we use `pulsar.getLookupServiceAddress()` instead?



##########
pulsar-broker/src/main/java/org/apache/pulsar/broker/loadbalance/extensions/BrokerRegistryImpl.java:
##########
@@ -0,0 +1,218 @@
+/*
+ * 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 com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.Lists;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.CompletionException;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.RejectedExecutionException;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.function.BiConsumer;
+import lombok.extern.slf4j.Slf4j;
+import org.apache.pulsar.broker.PulsarServerException;
+import org.apache.pulsar.broker.PulsarService;
+import org.apache.pulsar.broker.ServiceConfiguration;
+import org.apache.pulsar.broker.loadbalance.extensions.data.BrokerLookupData;
+import org.apache.pulsar.common.util.FutureUtil;
+import org.apache.pulsar.metadata.api.MetadataStoreException;
+import org.apache.pulsar.metadata.api.Notification;
+import org.apache.pulsar.metadata.api.NotificationType;
+import org.apache.pulsar.metadata.api.coordination.LockManager;
+import org.apache.pulsar.metadata.api.coordination.ResourceLock;
+
+/**
+ * The broker registry impl, base on the LockManager.
+ */
+@Slf4j
+public class BrokerRegistryImpl implements BrokerRegistry {
+
+    private static final String LOOKUP_DATA_PATH = "/loadbalance/brokers";
+
+    private final PulsarService pulsar;
+
+    private final ServiceConfiguration conf;
+
+    private final BrokerLookupData brokerLookupData;
+
+    private final LockManager<BrokerLookupData> brokerLookupDataLockManager;
+
+    private final String brokerZNodePath;
+
+    private final String lookupServiceAddress;
+
+    @VisibleForTesting
+    protected final Map<String, BrokerLookupData> brokerLookupDataMap;
+
+    private final ScheduledExecutorService scheduler;
+
+    private final List<BiConsumer<String, NotificationType>> listeners;
+
+    private final AtomicBoolean registered;
+
+    private volatile ResourceLock<BrokerLookupData> brokerLookupDataLock;
+
+    public BrokerRegistryImpl(PulsarService pulsar) {
+        this.pulsar = pulsar;
+        this.conf = pulsar.getConfiguration();
+        this.brokerLookupDataLockManager = 
pulsar.getCoordinationService().getLockManager(BrokerLookupData.class);
+        this.scheduler = pulsar.getLoadManagerExecutor();
+        this.brokerLookupDataMap = new ConcurrentHashMap<>();
+        this.listeners = new ArrayList<>();
+
+        this.registered = new AtomicBoolean(false);
+        this.lookupServiceAddress = pulsar.getAdvertisedAddress() + ":"
+                + conf.getWebServicePort().orElseGet(() -> 
conf.getWebServicePortTls().get());
+        this.brokerZNodePath = LOOKUP_DATA_PATH + "/" + lookupServiceAddress;
+        this.brokerLookupData = new BrokerLookupData(
+                pulsar.getSafeWebServiceAddress(),
+                pulsar.getWebServiceAddressTls(),
+                pulsar.getBrokerServiceUrl(),
+                pulsar.getBrokerServiceUrlTls(),
+                pulsar.getAdvertisedListeners(),
+                pulsar.getProtocolDataToAdvertise(),
+                pulsar.getConfiguration().isEnablePersistentTopics(),
+                pulsar.getConfiguration().isEnableNonPersistentTopics(),
+                pulsar.getBrokerVersion());
+    }
+
+    @Override
+    public void start() {
+        
pulsar.getLocalMetadataStore().registerListener(this::handleMetadataStoreNotification);
+    }
+
+    @Override
+    public void register() {
+        if (registered.compareAndSet(false, true)) {

Review Comment:
   what if `brokerLookupDataLockManager .acquireLock(..)` fails (but we pre-set 
`registered` to true in this case)?



##########
pulsar-broker/src/main/java/org/apache/pulsar/broker/loadbalance/extensions/BrokerRegistryImpl.java:
##########
@@ -0,0 +1,218 @@
+/*
+ * 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 com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.Lists;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.CompletionException;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.RejectedExecutionException;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.function.BiConsumer;
+import lombok.extern.slf4j.Slf4j;
+import org.apache.pulsar.broker.PulsarServerException;
+import org.apache.pulsar.broker.PulsarService;
+import org.apache.pulsar.broker.ServiceConfiguration;
+import org.apache.pulsar.broker.loadbalance.extensions.data.BrokerLookupData;
+import org.apache.pulsar.common.util.FutureUtil;
+import org.apache.pulsar.metadata.api.MetadataStoreException;
+import org.apache.pulsar.metadata.api.Notification;
+import org.apache.pulsar.metadata.api.NotificationType;
+import org.apache.pulsar.metadata.api.coordination.LockManager;
+import org.apache.pulsar.metadata.api.coordination.ResourceLock;
+
+/**
+ * The broker registry impl, base on the LockManager.
+ */
+@Slf4j
+public class BrokerRegistryImpl implements BrokerRegistry {
+
+    private static final String LOOKUP_DATA_PATH = "/loadbalance/brokers";
+
+    private final PulsarService pulsar;
+
+    private final ServiceConfiguration conf;
+
+    private final BrokerLookupData brokerLookupData;
+
+    private final LockManager<BrokerLookupData> brokerLookupDataLockManager;
+
+    private final String brokerZNodePath;
+
+    private final String lookupServiceAddress;
+
+    @VisibleForTesting
+    protected final Map<String, BrokerLookupData> brokerLookupDataMap;
+
+    private final ScheduledExecutorService scheduler;
+
+    private final List<BiConsumer<String, NotificationType>> listeners;
+
+    private final AtomicBoolean registered;
+
+    private volatile ResourceLock<BrokerLookupData> brokerLookupDataLock;
+
+    public BrokerRegistryImpl(PulsarService pulsar) {
+        this.pulsar = pulsar;
+        this.conf = pulsar.getConfiguration();
+        this.brokerLookupDataLockManager = 
pulsar.getCoordinationService().getLockManager(BrokerLookupData.class);
+        this.scheduler = pulsar.getLoadManagerExecutor();
+        this.brokerLookupDataMap = new ConcurrentHashMap<>();
+        this.listeners = new ArrayList<>();
+
+        this.registered = new AtomicBoolean(false);
+        this.lookupServiceAddress = pulsar.getAdvertisedAddress() + ":"
+                + conf.getWebServicePort().orElseGet(() -> 
conf.getWebServicePortTls().get());
+        this.brokerZNodePath = LOOKUP_DATA_PATH + "/" + lookupServiceAddress;
+        this.brokerLookupData = new BrokerLookupData(
+                pulsar.getSafeWebServiceAddress(),
+                pulsar.getWebServiceAddressTls(),
+                pulsar.getBrokerServiceUrl(),
+                pulsar.getBrokerServiceUrlTls(),
+                pulsar.getAdvertisedListeners(),
+                pulsar.getProtocolDataToAdvertise(),
+                pulsar.getConfiguration().isEnablePersistentTopics(),
+                pulsar.getConfiguration().isEnableNonPersistentTopics(),
+                pulsar.getBrokerVersion());
+    }
+
+    @Override
+    public void start() {
+        
pulsar.getLocalMetadataStore().registerListener(this::handleMetadataStoreNotification);
+    }
+
+    @Override
+    public void register() {
+        if (registered.compareAndSet(false, true)) {
+            this.brokerLookupDataLock =
+                    brokerLookupDataLockManager.acquireLock(brokerZNodePath, 
brokerLookupData).join();
+        }
+    }
+
+    @Override
+    public void unregister() throws MetadataStoreException {
+        if (registered.compareAndSet(true, false)) {
+            try {
+                brokerLookupDataLock.release().join();
+            } catch (CompletionException e) {
+                throw MetadataStoreException.unwrap(e);
+            }
+        }
+    }
+
+    @Override
+    public String getLookupServiceAddress() {
+        return this.lookupServiceAddress;
+    }
+
+    @Override
+    public CompletableFuture<List<String>> getAvailableBrokersAsync() {
+        CompletableFuture<List<String>> future = new CompletableFuture<>();
+        brokerLookupDataLockManager.listLocks(LOOKUP_DATA_PATH)
+                .thenAccept(listLocks -> 
future.complete(Lists.newArrayList(listLocks)))
+                .exceptionally(ex -> {
+                    Throwable realCause = 
FutureUtil.unwrapCompletionException(ex);
+                    log.warn("Error when trying to get active brokers", 
realCause);
+                    
future.complete(Lists.newArrayList(this.brokerLookupDataMap.keySet()));
+                    return null;
+                });
+        return future;
+    }
+
+    @Override
+    public CompletableFuture<Optional<BrokerLookupData>> lookupAsync(String 
broker) {
+        return brokerLookupDataLockManager.readLock(keyPath(broker));
+    }
+
+    @Override
+    public void forEach(BiConsumer<String, BrokerLookupData> action) {
+        this.brokerLookupDataMap.forEach(action);
+    }
+
+    public void listen(BiConsumer<String, NotificationType> listener) {
+        this.listeners.add(listener);
+    }
+
+    @Override
+    public void close() throws PulsarServerException {
+        try {
+            this.unregister();
+        } catch (MetadataStoreException ex) {
+            if (ex.getCause() instanceof 
MetadataStoreException.NotFoundException) {
+                throw new 
PulsarServerException.NotFoundException(MetadataStoreException.unwrap(ex));
+            } else {
+                throw new 
PulsarServerException(MetadataStoreException.unwrap(ex));
+            }
+        }
+
+        this.listeners.clear();
+    }
+
+    private void handleMetadataStoreNotification(Notification t) {
+        if (t.getPath().startsWith(LOOKUP_DATA_PATH) && t.getPath().length() > 
LOOKUP_DATA_PATH.length()) {
+            try {
+                if (log.isDebugEnabled()) {
+                    log.debug("Handle notification: [{}]", t);
+                }
+                this.scheduler.submit(() -> {
+                    String lookupServiceAddress = 
t.getPath().substring(LOOKUP_DATA_PATH.length() + 1);
+                    
this.updateBrokerLookupDataToLocalCache(lookupServiceAddress, t.getType());
+                    for (BiConsumer<String, NotificationType> listener : 
listeners) {
+                        listener.accept(lookupServiceAddress, t.getType());
+                    }
+                });
+            } catch (RejectedExecutionException e) {
+                // Executor is shutting down
+            }
+        }
+    }
+
+    private void updateBrokerLookupDataToLocalCache(String 
lookupServiceAddress, NotificationType type) {
+        switch (type) {
+            case Created, Modified, ChildrenChanged -> {
+                try {
+                    Optional<BrokerLookupData> lookupData =
+                            
brokerLookupDataLockManager.readLock(keyPath(lookupServiceAddress))
+                                    
.get(conf.getMetadataStoreOperationTimeoutSeconds(), TimeUnit.SECONDS);
+                    if (lookupData.isEmpty()) {
+                        brokerLookupDataMap.remove(lookupServiceAddress);
+                        log.info("[{}] Broker lookup data is not present", 
lookupServiceAddress);
+                        break;
+                    }
+                    brokerLookupDataMap.put(lookupServiceAddress, 
lookupData.get());
+                } catch (Exception e) {
+                    log.warn("Error reading broker data from cache for broker 
- [{}], [{}]",

Review Comment:
   In this case, this `brokerLookupDataMap` cache can be inconsistent from 
others. Can we make this cache update eventually consistent?



##########
pulsar-broker/src/test/java/org/apache/pulsar/broker/loadbalance/extensions/BrokerRegistryTest.java:
##########
@@ -0,0 +1,244 @@
+/*
+ * 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 static org.testng.Assert.assertEquals;
+import static org.testng.Assert.assertTrue;
+
+import java.time.Duration;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Optional;
+import java.util.Set;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.LinkedBlockingQueue;
+import java.util.concurrent.ThreadPoolExecutor;
+import java.util.concurrent.TimeUnit;
+import org.apache.bookkeeper.util.ZkUtils;
+import org.apache.pulsar.broker.PulsarServerException;
+import org.apache.pulsar.broker.PulsarService;
+import org.apache.pulsar.broker.ServiceConfiguration;
+import org.apache.pulsar.broker.loadbalance.LoadManager;
+import org.apache.pulsar.broker.loadbalance.ResourceUnit;
+import org.apache.pulsar.broker.loadbalance.extensions.data.BrokerLookupData;
+import org.apache.pulsar.common.naming.ServiceUnitId;
+import org.apache.pulsar.common.policies.data.ClusterData;
+import org.apache.pulsar.common.stats.Metrics;
+import org.apache.pulsar.common.util.ObjectMapperFactory;
+import org.apache.pulsar.policies.data.loadbalancer.LoadManagerReport;
+import org.apache.pulsar.zookeeper.LocalBookkeeperEnsemble;
+import org.apache.zookeeper.CreateMode;
+import org.apache.zookeeper.ZooDefs;
+import org.apache.zookeeper.ZooKeeper;
+import org.awaitility.Awaitility;
+import org.testng.annotations.AfterMethod;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+
+
+/**
+ * Unit test for {@link BrokerRegistry}.
+ */
+public class BrokerRegistryTest {
+
+    private ExecutorService executor;
+
+    private LocalBookkeeperEnsemble bkEnsemble;
+
+    private PulsarService pulsar1;
+
+    private PulsarService pulsar2;
+
+    // Make sure the load manager don't register itself to 
`/loadbalance/brokers/{lookupServiceAddress}`
+    public static class MockLoadManager implements LoadManager {
+
+        @Override
+        public void start() throws PulsarServerException {
+            // No-op
+        }
+
+        @Override
+        public boolean isCentralized() {
+            return false;
+        }
+
+        @Override
+        public Optional<ResourceUnit> getLeastLoaded(ServiceUnitId su) throws 
Exception {
+            return Optional.empty();
+        }
+
+        @Override
+        public LoadManagerReport generateLoadReport() throws Exception {
+            return null;
+        }
+
+        @Override
+        public void setLoadReportForceUpdateFlag() {
+            // No-op
+        }
+
+        @Override
+        public void writeLoadReportOnZookeeper() throws Exception {
+            // No-op
+        }
+
+        @Override
+        public void writeResourceQuotasToZooKeeper() throws Exception {
+            // No-op
+        }
+
+        @Override
+        public List<Metrics> getLoadBalancingMetrics() {
+            return null;
+        }
+
+        @Override
+        public void doLoadShedding() {
+            // No-op
+        }
+
+        @Override
+        public void doNamespaceBundleSplit() throws Exception {
+            // No-op
+        }
+
+        @Override
+        public void disableBroker() throws Exception {
+            // No-op
+        }
+
+        @Override
+        public Set<String> getAvailableBrokers() throws Exception {
+            return null;
+        }
+
+        @Override
+        public CompletableFuture<Set<String>> getAvailableBrokersAsync() {
+            return null;
+        }
+
+        @Override
+        public void stop() throws PulsarServerException {
+            // No-op
+        }
+
+        @Override
+        public void initialize(PulsarService pulsar) {
+            // No-op
+        }
+    }
+
+    @BeforeMethod
+    void setup() throws Exception {
+        executor = new ThreadPoolExecutor(5, 20, 30, TimeUnit.SECONDS,
+                new LinkedBlockingQueue<>());
+        // Start local bookkeeper ensemble
+        bkEnsemble = new LocalBookkeeperEnsemble(3, 0, () -> 0);
+        bkEnsemble.start();
+
+        // Start broker 1
+        ServiceConfiguration config1 = new ServiceConfiguration();
+        config1.setLoadBalancerEnabled(false);
+        config1.setLoadManagerClassName(MockLoadManager.class.getName());
+        config1.setClusterName("use");
+        config1.setWebServicePort(Optional.of(0));
+        config1.setMetadataStoreUrl("zk:127.0.0.1" + ":" + 
bkEnsemble.getZookeeperPort());
+        config1.setBrokerShutdownTimeoutMs(0L);
+        config1.setBrokerServicePort(Optional.of(0));
+        config1.setAdvertisedAddress("localhost");
+        createCluster(bkEnsemble.getZkClient(), config1);
+        pulsar1 = new PulsarService(config1);
+        pulsar1.start();
+
+        // Start broker 2
+        ServiceConfiguration config2 = new ServiceConfiguration();
+        config2.setLoadBalancerEnabled(false);
+        config2.setLoadManagerClassName(MockLoadManager.class.getName());
+        config2.setClusterName("use");
+        config2.setWebServicePort(Optional.of(0));
+        config2.setMetadataStoreUrl("zk:127.0.0.1" + ":" + 
bkEnsemble.getZookeeperPort());
+        config2.setBrokerShutdownTimeoutMs(0L);
+        config2.setBrokerServicePort(Optional.of(0));
+        config2.setAdvertisedAddress("localhost");
+        pulsar2 = new PulsarService(config2);
+        pulsar2.start();
+    }
+
+    @AfterMethod(alwaysRun = true)
+    void shutdown() throws Exception {
+        executor.shutdownNow();
+
+        pulsar2.close();
+        pulsar1.close();
+
+        bkEnsemble.stop();
+    }
+

Review Comment:
   Maybe we can add more UTs for unhappy cases(when metadata store read/write 
fails).



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


Reply via email to