heesung-sn commented on code in PR #18489: URL: https://github.com/apache/pulsar/pull/18489#discussion_r1026849908
########## pulsar-broker/src/main/java/org/apache/pulsar/broker/loadbalance/extensions/channel/ServiceUnitStateChannelImpl.java: ########## @@ -0,0 +1,779 @@ +/* + * 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.channel; + +import static org.apache.pulsar.broker.loadbalance.extensions.channel.ServiceUnitState.Assigned; +import static org.apache.pulsar.broker.loadbalance.extensions.channel.ServiceUnitState.Owned; +import static org.apache.pulsar.broker.loadbalance.extensions.channel.ServiceUnitState.Released; +import static org.apache.pulsar.broker.loadbalance.extensions.channel.ServiceUnitState.Splitting; +import static org.apache.pulsar.broker.loadbalance.extensions.channel.ServiceUnitStateChannelImpl.MetadataState.Jittery; +import static org.apache.pulsar.broker.loadbalance.extensions.channel.ServiceUnitStateChannelImpl.MetadataState.Stable; +import static org.apache.pulsar.broker.loadbalance.extensions.channel.ServiceUnitStateChannelImpl.MetadataState.Unstable; +import static org.apache.pulsar.metadata.api.extended.SessionEvent.SessionLost; +import static org.apache.pulsar.metadata.api.extended.SessionEvent.SessionReestablished; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.Set; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.Executor; +import java.util.concurrent.ScheduledFuture; +import java.util.concurrent.Semaphore; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.lang3.StringUtils; +import org.apache.commons.lang3.mutable.MutableInt; +import org.apache.pulsar.broker.PulsarServerException; +import org.apache.pulsar.broker.PulsarService; +import org.apache.pulsar.broker.ServiceConfiguration; +import org.apache.pulsar.broker.loadbalance.LeaderBroker; +import org.apache.pulsar.broker.loadbalance.LeaderElectionService; +import org.apache.pulsar.broker.loadbalance.extensions.models.Split; +import org.apache.pulsar.broker.loadbalance.extensions.models.Unload; +import org.apache.pulsar.broker.loadbalance.impl.LoadManagerShared; +import org.apache.pulsar.client.admin.PulsarAdminException; +import org.apache.pulsar.client.api.MessageId; +import org.apache.pulsar.client.api.Producer; +import org.apache.pulsar.client.api.Schema; +import org.apache.pulsar.client.api.TableView; +import org.apache.pulsar.common.naming.NamespaceBundle; +import org.apache.pulsar.common.naming.NamespaceBundleSplitAlgorithm; +import org.apache.pulsar.common.naming.NamespaceName; +import org.apache.pulsar.common.naming.TopicDomain; +import org.apache.pulsar.common.util.collections.ConcurrentOpenHashMap; +import org.apache.pulsar.metadata.api.NotificationType; +import org.apache.pulsar.metadata.api.coordination.LeaderElectionState; +import org.apache.pulsar.metadata.api.extended.SessionEvent; + +@Slf4j +public class ServiceUnitStateChannelImpl implements ServiceUnitStateChannel { + public static final String TOPIC = + TopicDomain.persistent.value() + + "://" + + NamespaceName.SYSTEM_NAMESPACE + + "/service-unit-state-channel"; + private static final Schema<ServiceUnitStateData> SCHEMA = Schema.JSON(ServiceUnitStateData.class); + // TODO: define StateCompactionStrategy + private static final long COMPACTION_THRESHOLD = 5 * 1024 * 1024; // 5mb + private static final long MAX_IN_FLIGHT_STATE_WAITING_TIME_IN_MILLIS = 30 * 1000; // 30sec + public static final long MAX_CLEAN_UP_DELAY_TIME_IN_SECS = 3 * 60; // 3 mins + private static final long MIN_CLEAN_UP_DELAY_TIME_IN_SECS = 0; // 0 secs to clean immediately + private static final int MAX_OUTSTANDING_PUB_MESSAGES = 500; + private final PulsarService pulsar; + private TableView<ServiceUnitStateData> tableview; + private Producer<ServiceUnitStateData> producer; + private final ConcurrentOpenHashMap<String, CompletableFuture<String>> getOwnerRequests; + private String lookupServiceAddress; + private LeaderElectionService leaderElectionService; + // TODO: define BrokerRegistry + private SessionEvent lastMetadataSessionEvent = SessionReestablished; + private long lastMetadataSessionEventTimestamp = 0; + private Semaphore outstandingPubMessages; + + private Semaphore outstandingCleanupTombstoneMessages; + private ScheduledFuture<?> cleanupTasks; + private long inFlightStateWaitingTimeInMillis; + private long maxCleanupDelayTimeInSecs; + private long minCleanupDelayTimeInSecs; + + private ConcurrentOpenHashMap<String, CompletableFuture<Void>> cleanupJobs; + + // cleanup metrics + private long totalCleanupCnt = 0; + private long totalBrokerCleanupTombstoneCnt = 0; + private long totalServiceUnitCleanupTombstoneCnt = 0; + private long totalServiceUnitCleanupErrorCnt = 0; + private long totalCleanupScheduledCnt = 0; + private long totalCleanupIgnoredCnt = 0; + private long totalCleanupCancelledCnt = 0; + + + enum MetadataState { + Stable, + Jittery, + Unstable + } + + public ServiceUnitStateChannelImpl(PulsarService pulsar) { + this.pulsar = pulsar; + ServiceConfiguration conf = pulsar.getConfiguration(); + this.lookupServiceAddress = pulsar.getAdvertisedAddress() + ":" + + (conf.getWebServicePort().isPresent() ? conf.getWebServicePort().get() + : conf.getWebServicePortTls().get()); + this.outstandingPubMessages = new Semaphore(MAX_OUTSTANDING_PUB_MESSAGES); + this.outstandingCleanupTombstoneMessages = new Semaphore(MAX_OUTSTANDING_PUB_MESSAGES); + this.getOwnerRequests = ConcurrentOpenHashMap.<String, + CompletableFuture<String>>newBuilder() + .build(); + this.cleanupJobs = + ConcurrentOpenHashMap.<String, CompletableFuture<Void>>newBuilder() + .build(); + this.inFlightStateWaitingTimeInMillis = MAX_IN_FLIGHT_STATE_WAITING_TIME_IN_MILLIS; + this.maxCleanupDelayTimeInSecs = MAX_CLEAN_UP_DELAY_TIME_IN_SECS; + this.minCleanupDelayTimeInSecs = MIN_CLEAN_UP_DELAY_TIME_IN_SECS; + } + + public void start() throws PulsarServerException { + + try { + if (leaderElectionService != null) { + leaderElectionService.close(); + log.debug("Closed the channel leader election service."); + } + this.leaderElectionService = new LeaderElectionService( + pulsar.getCoordinationService(), pulsar.getSafeWebServiceAddress(), + state -> { + if (state == LeaderElectionState.Leading) { + log.debug("This broker:{} was elected as the leader." + + "Current channel leader is {}", + lookupServiceAddress, + leaderElectionService.getCurrentLeader()); + } else { + if (leaderElectionService != null) { + log.debug("This broker:{} is a follower. " + + "Current channel leader is {}", + lookupServiceAddress, + leaderElectionService.getCurrentLeader()); + } + } + }); + leaderElectionService.start(); + log.debug("Successfully started the channel leader election service."); + + if (producer != null) { + producer.close(); + log.debug("Closed the channel producer."); + } + producer = pulsar.getClient().newProducer(SCHEMA) + .enableBatching(true) + .topic(TOPIC) + .create(); + + log.debug("Successfully started the channel producer."); + + if (tableview != null) { + tableview.close(); + log.debug("Closed the channel tableview."); + } + tableview = pulsar.getClient().newTableViewBuilder(SCHEMA) + .topic(TOPIC) + // TODO: enable CompactionStrategy + .create(); + // TODO: schedule listen instead of foreachAndListen + tableview.forEachAndListen((key, value) -> handle(key, value)); + log.debug("Successfully started the channel tableview."); + + // TODO: schedule cleanupTasks by brokerRegistry + pulsar.getLocalMetadataStore().registerSessionListener(this::handleMetadataSessionEvent); + log.debug("Successfully registered the handleMetadataSessionEvent"); + + log.info("Successfully started the channel."); + } catch (Exception e) { + String msg = "Failed to start the channel."; + log.error(msg, e); + throw new PulsarServerException(msg, e); + } + } + + + public void close() throws PulsarServerException { + try { + if (leaderElectionService != null) { + leaderElectionService.close(); + leaderElectionService = null; + log.debug("Successfully closed the channel leader election service."); + } + + if (tableview != null) { + tableview.close(); + tableview = null; + log.debug("Successfully closed the channel tableview."); + } + + if (producer != null) { + producer.close(); + producer = null; + log.info("Successfully closed the channel producer."); + } + + // TODO: clean brokerRegistry + + if (cleanupTasks != null) { + cleanupTasks.cancel(true); + cleanupTasks = null; + log.info("Successfully cancelled the cleanup tasks"); + } + + log.info("Successfully closed the channel."); + + } catch (Exception e) { + String msg = "Failed to close the channel."; + log.error(msg, e); + throw new PulsarServerException(msg, e); + } + } + + public void scheduleCompaction() throws PulsarServerException { + try { + Long threshold = pulsar.getAdminClient().topicPolicies() + .getCompactionThreshold(TOPIC); + if (threshold == null || threshold == 0) { + pulsar.getAdminClient().topicPolicies() + .setCompactionThreshold(TOPIC, COMPACTION_THRESHOLD); + log.info("Scheduled compaction on topic:{}, threshold:{} bytes", TOPIC, COMPACTION_THRESHOLD); + } else { + log.info("Already set compaction on topic:{}, threshold:{} bytes", TOPIC, COMPACTION_THRESHOLD); + } + } catch (PulsarAdminException e) { + throw new PulsarServerException("Failed to schedule compaction.", e); + } + } + + public String getChannelOwner() { + CompletableFuture<Optional<LeaderBroker>> future = leaderElectionService.readCurrentLeader(); + if (!future.isDone()) { + return null; + } + Optional<LeaderBroker> leader = future.join(); + if (leader.isEmpty()) { + return null; + } + //expecting http://broker-xyz:port + String broker = leader.get().getServiceUrl(); + broker = broker.substring(broker.lastIndexOf('/') + 1); + return broker; + } + + public boolean isChannelOwner() { + return isTargetBroker(getChannelOwner()); + } + + public CompletableFuture<String> getOwnerAsync(String serviceUnit) { + + ServiceUnitStateData data = tableview.get(serviceUnit); + if (data == null) { + return null; + } + switch (data.state()) { + case Owned, Splitting -> { + return CompletableFuture.completedFuture(data.broker()); + } + case Assigned, Released -> { + return deferGetOwnerRequest(serviceUnit); + } + default -> { + return null; + } + } + } + + public CompletableFuture<String> publishAssignEventAsync(String serviceUnit, String broker) { + CompletableFuture<String> getOwnerRequest = deferGetOwnerRequest(serviceUnit); + pubAsync(serviceUnit, new ServiceUnitStateData(Assigned, broker)) + .whenComplete((__, ex) -> { + if (ex != null) { + getOwnerRequests.remove(serviceUnit); + if (!getOwnerRequest.isCompletedExceptionally()) { + getOwnerRequest.completeExceptionally(ex); + } + } + }); + + return getOwnerRequest; + } + + public CompletableFuture<Void> publishUnloadEventAsync(Unload unload) { + String serviceUnit = unload.serviceUnit(); + if (isTransferCommand(unload)) { + ServiceUnitStateData next = new ServiceUnitStateData(Assigned, + unload.destBroker().get(), unload.sourceBroker()); + return pubAsync(serviceUnit, next).thenAccept(__ -> { + }); + } + return tombstoneAsync(serviceUnit).thenAccept(__ -> { + }); + } + + public CompletableFuture<Void> publishSplitEventAsync(Split split) { + String serviceUnit = split.serviceUnit(); + ServiceUnitStateData data = tableview.get(serviceUnit); + ServiceUnitStateData next = new ServiceUnitStateData(Splitting, data.broker()); + return pubAsync(serviceUnit, next).thenAccept(__ -> { + }); + } + + private void handle(String serviceUnit, ServiceUnitStateData data) { + if (log.isDebugEnabled()) { + log.info("{} received a handle request for serviceUnit:{}, data:{}", + lookupServiceAddress, serviceUnit, data); + } + + if (data == null) { + handleTombstoneEvent(serviceUnit); + return; + } + + // TODO : Add state validation + switch (data.state()) { + case Owned -> handleOwnEvent(serviceUnit, data); + case Assigned -> handleAssignEvent(serviceUnit, data); + case Released -> handleReleaseEvent(serviceUnit, data); + case Splitting -> handleSplitEvent(serviceUnit, data); + default -> throw new IllegalStateException("Failed to handle channel data:" + data); + } + } + + private static boolean isTransferCommand(ServiceUnitStateData data) { + if (data == null) { + return false; + } + return StringUtils.isNotEmpty(data.sourceBroker()); + } + + private static boolean isTransferCommand(Unload data) { + return data.destBroker().isPresent(); + } + + private static String getLogEventTag(ServiceUnitStateData data) { + return data == null ? "Free" : + isTransferCommand(data) ? "Transfer:" + data.state() : data.state().toString(); + } + + private void log(Throwable e, String serviceUnit, ServiceUnitStateData data, ServiceUnitStateData next) { Review Comment: No. It can't. `lookupServiceAddress` is a member var. ########## pulsar-broker/src/main/java/org/apache/pulsar/broker/loadbalance/extensions/channel/ServiceUnitStateChannelImpl.java: ########## @@ -0,0 +1,779 @@ +/* + * 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.channel; + +import static org.apache.pulsar.broker.loadbalance.extensions.channel.ServiceUnitState.Assigned; +import static org.apache.pulsar.broker.loadbalance.extensions.channel.ServiceUnitState.Owned; +import static org.apache.pulsar.broker.loadbalance.extensions.channel.ServiceUnitState.Released; +import static org.apache.pulsar.broker.loadbalance.extensions.channel.ServiceUnitState.Splitting; +import static org.apache.pulsar.broker.loadbalance.extensions.channel.ServiceUnitStateChannelImpl.MetadataState.Jittery; +import static org.apache.pulsar.broker.loadbalance.extensions.channel.ServiceUnitStateChannelImpl.MetadataState.Stable; +import static org.apache.pulsar.broker.loadbalance.extensions.channel.ServiceUnitStateChannelImpl.MetadataState.Unstable; +import static org.apache.pulsar.metadata.api.extended.SessionEvent.SessionLost; +import static org.apache.pulsar.metadata.api.extended.SessionEvent.SessionReestablished; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.Set; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.Executor; +import java.util.concurrent.ScheduledFuture; +import java.util.concurrent.Semaphore; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.lang3.StringUtils; +import org.apache.commons.lang3.mutable.MutableInt; +import org.apache.pulsar.broker.PulsarServerException; +import org.apache.pulsar.broker.PulsarService; +import org.apache.pulsar.broker.ServiceConfiguration; +import org.apache.pulsar.broker.loadbalance.LeaderBroker; +import org.apache.pulsar.broker.loadbalance.LeaderElectionService; +import org.apache.pulsar.broker.loadbalance.extensions.models.Split; +import org.apache.pulsar.broker.loadbalance.extensions.models.Unload; +import org.apache.pulsar.broker.loadbalance.impl.LoadManagerShared; +import org.apache.pulsar.client.admin.PulsarAdminException; +import org.apache.pulsar.client.api.MessageId; +import org.apache.pulsar.client.api.Producer; +import org.apache.pulsar.client.api.Schema; +import org.apache.pulsar.client.api.TableView; +import org.apache.pulsar.common.naming.NamespaceBundle; +import org.apache.pulsar.common.naming.NamespaceBundleSplitAlgorithm; +import org.apache.pulsar.common.naming.NamespaceName; +import org.apache.pulsar.common.naming.TopicDomain; +import org.apache.pulsar.common.util.collections.ConcurrentOpenHashMap; +import org.apache.pulsar.metadata.api.NotificationType; +import org.apache.pulsar.metadata.api.coordination.LeaderElectionState; +import org.apache.pulsar.metadata.api.extended.SessionEvent; + +@Slf4j +public class ServiceUnitStateChannelImpl implements ServiceUnitStateChannel { + public static final String TOPIC = + TopicDomain.persistent.value() + + "://" + + NamespaceName.SYSTEM_NAMESPACE + + "/service-unit-state-channel"; + private static final Schema<ServiceUnitStateData> SCHEMA = Schema.JSON(ServiceUnitStateData.class); + // TODO: define StateCompactionStrategy + private static final long COMPACTION_THRESHOLD = 5 * 1024 * 1024; // 5mb + private static final long MAX_IN_FLIGHT_STATE_WAITING_TIME_IN_MILLIS = 30 * 1000; // 30sec + public static final long MAX_CLEAN_UP_DELAY_TIME_IN_SECS = 3 * 60; // 3 mins + private static final long MIN_CLEAN_UP_DELAY_TIME_IN_SECS = 0; // 0 secs to clean immediately + private static final int MAX_OUTSTANDING_PUB_MESSAGES = 500; + private final PulsarService pulsar; + private TableView<ServiceUnitStateData> tableview; + private Producer<ServiceUnitStateData> producer; + private final ConcurrentOpenHashMap<String, CompletableFuture<String>> getOwnerRequests; + private String lookupServiceAddress; + private LeaderElectionService leaderElectionService; + // TODO: define BrokerRegistry + private SessionEvent lastMetadataSessionEvent = SessionReestablished; + private long lastMetadataSessionEventTimestamp = 0; + private Semaphore outstandingPubMessages; + + private Semaphore outstandingCleanupTombstoneMessages; + private ScheduledFuture<?> cleanupTasks; + private long inFlightStateWaitingTimeInMillis; + private long maxCleanupDelayTimeInSecs; + private long minCleanupDelayTimeInSecs; + + private ConcurrentOpenHashMap<String, CompletableFuture<Void>> cleanupJobs; + + // cleanup metrics + private long totalCleanupCnt = 0; + private long totalBrokerCleanupTombstoneCnt = 0; + private long totalServiceUnitCleanupTombstoneCnt = 0; + private long totalServiceUnitCleanupErrorCnt = 0; + private long totalCleanupScheduledCnt = 0; + private long totalCleanupIgnoredCnt = 0; + private long totalCleanupCancelledCnt = 0; + + + enum MetadataState { + Stable, + Jittery, + Unstable + } + + public ServiceUnitStateChannelImpl(PulsarService pulsar) { + this.pulsar = pulsar; + ServiceConfiguration conf = pulsar.getConfiguration(); + this.lookupServiceAddress = pulsar.getAdvertisedAddress() + ":" + + (conf.getWebServicePort().isPresent() ? conf.getWebServicePort().get() + : conf.getWebServicePortTls().get()); + this.outstandingPubMessages = new Semaphore(MAX_OUTSTANDING_PUB_MESSAGES); + this.outstandingCleanupTombstoneMessages = new Semaphore(MAX_OUTSTANDING_PUB_MESSAGES); + this.getOwnerRequests = ConcurrentOpenHashMap.<String, + CompletableFuture<String>>newBuilder() + .build(); + this.cleanupJobs = + ConcurrentOpenHashMap.<String, CompletableFuture<Void>>newBuilder() + .build(); + this.inFlightStateWaitingTimeInMillis = MAX_IN_FLIGHT_STATE_WAITING_TIME_IN_MILLIS; + this.maxCleanupDelayTimeInSecs = MAX_CLEAN_UP_DELAY_TIME_IN_SECS; + this.minCleanupDelayTimeInSecs = MIN_CLEAN_UP_DELAY_TIME_IN_SECS; + } + + public void start() throws PulsarServerException { + + try { + if (leaderElectionService != null) { + leaderElectionService.close(); + log.debug("Closed the channel leader election service."); + } + this.leaderElectionService = new LeaderElectionService( + pulsar.getCoordinationService(), pulsar.getSafeWebServiceAddress(), + state -> { + if (state == LeaderElectionState.Leading) { + log.debug("This broker:{} was elected as the leader." + + "Current channel leader is {}", + lookupServiceAddress, + leaderElectionService.getCurrentLeader()); + } else { + if (leaderElectionService != null) { + log.debug("This broker:{} is a follower. " + + "Current channel leader is {}", + lookupServiceAddress, + leaderElectionService.getCurrentLeader()); + } + } + }); + leaderElectionService.start(); + log.debug("Successfully started the channel leader election service."); + + if (producer != null) { + producer.close(); + log.debug("Closed the channel producer."); + } + producer = pulsar.getClient().newProducer(SCHEMA) + .enableBatching(true) + .topic(TOPIC) + .create(); + + log.debug("Successfully started the channel producer."); + + if (tableview != null) { + tableview.close(); + log.debug("Closed the channel tableview."); + } + tableview = pulsar.getClient().newTableViewBuilder(SCHEMA) + .topic(TOPIC) + // TODO: enable CompactionStrategy + .create(); + // TODO: schedule listen instead of foreachAndListen + tableview.forEachAndListen((key, value) -> handle(key, value)); + log.debug("Successfully started the channel tableview."); + + // TODO: schedule cleanupTasks by brokerRegistry + pulsar.getLocalMetadataStore().registerSessionListener(this::handleMetadataSessionEvent); + log.debug("Successfully registered the handleMetadataSessionEvent"); + + log.info("Successfully started the channel."); + } catch (Exception e) { + String msg = "Failed to start the channel."; + log.error(msg, e); + throw new PulsarServerException(msg, e); + } + } + + + public void close() throws PulsarServerException { + try { + if (leaderElectionService != null) { + leaderElectionService.close(); + leaderElectionService = null; + log.debug("Successfully closed the channel leader election service."); + } + + if (tableview != null) { + tableview.close(); + tableview = null; + log.debug("Successfully closed the channel tableview."); + } + + if (producer != null) { + producer.close(); + producer = null; + log.info("Successfully closed the channel producer."); + } + + // TODO: clean brokerRegistry + + if (cleanupTasks != null) { + cleanupTasks.cancel(true); + cleanupTasks = null; + log.info("Successfully cancelled the cleanup tasks"); + } + + log.info("Successfully closed the channel."); + + } catch (Exception e) { + String msg = "Failed to close the channel."; + log.error(msg, e); + throw new PulsarServerException(msg, e); + } + } + + public void scheduleCompaction() throws PulsarServerException { + try { + Long threshold = pulsar.getAdminClient().topicPolicies() + .getCompactionThreshold(TOPIC); + if (threshold == null || threshold == 0) { + pulsar.getAdminClient().topicPolicies() + .setCompactionThreshold(TOPIC, COMPACTION_THRESHOLD); + log.info("Scheduled compaction on topic:{}, threshold:{} bytes", TOPIC, COMPACTION_THRESHOLD); + } else { + log.info("Already set compaction on topic:{}, threshold:{} bytes", TOPIC, COMPACTION_THRESHOLD); + } + } catch (PulsarAdminException e) { + throw new PulsarServerException("Failed to schedule compaction.", e); + } + } + + public String getChannelOwner() { + CompletableFuture<Optional<LeaderBroker>> future = leaderElectionService.readCurrentLeader(); + if (!future.isDone()) { + return null; + } + Optional<LeaderBroker> leader = future.join(); + if (leader.isEmpty()) { + return null; + } + //expecting http://broker-xyz:port + String broker = leader.get().getServiceUrl(); + broker = broker.substring(broker.lastIndexOf('/') + 1); + return broker; + } + + public boolean isChannelOwner() { + return isTargetBroker(getChannelOwner()); + } + + public CompletableFuture<String> getOwnerAsync(String serviceUnit) { + + ServiceUnitStateData data = tableview.get(serviceUnit); + if (data == null) { + return null; + } + switch (data.state()) { + case Owned, Splitting -> { + return CompletableFuture.completedFuture(data.broker()); + } + case Assigned, Released -> { + return deferGetOwnerRequest(serviceUnit); + } + default -> { + return null; + } + } + } + + public CompletableFuture<String> publishAssignEventAsync(String serviceUnit, String broker) { + CompletableFuture<String> getOwnerRequest = deferGetOwnerRequest(serviceUnit); + pubAsync(serviceUnit, new ServiceUnitStateData(Assigned, broker)) + .whenComplete((__, ex) -> { + if (ex != null) { + getOwnerRequests.remove(serviceUnit); + if (!getOwnerRequest.isCompletedExceptionally()) { + getOwnerRequest.completeExceptionally(ex); + } + } + }); + + return getOwnerRequest; + } + + public CompletableFuture<Void> publishUnloadEventAsync(Unload unload) { + String serviceUnit = unload.serviceUnit(); + if (isTransferCommand(unload)) { + ServiceUnitStateData next = new ServiceUnitStateData(Assigned, + unload.destBroker().get(), unload.sourceBroker()); + return pubAsync(serviceUnit, next).thenAccept(__ -> { + }); + } + return tombstoneAsync(serviceUnit).thenAccept(__ -> { + }); + } + + public CompletableFuture<Void> publishSplitEventAsync(Split split) { + String serviceUnit = split.serviceUnit(); + ServiceUnitStateData data = tableview.get(serviceUnit); + ServiceUnitStateData next = new ServiceUnitStateData(Splitting, data.broker()); + return pubAsync(serviceUnit, next).thenAccept(__ -> { + }); + } + + private void handle(String serviceUnit, ServiceUnitStateData data) { + if (log.isDebugEnabled()) { + log.info("{} received a handle request for serviceUnit:{}, data:{}", + lookupServiceAddress, serviceUnit, data); + } + + if (data == null) { + handleTombstoneEvent(serviceUnit); + return; + } + + // TODO : Add state validation + switch (data.state()) { + case Owned -> handleOwnEvent(serviceUnit, data); + case Assigned -> handleAssignEvent(serviceUnit, data); + case Released -> handleReleaseEvent(serviceUnit, data); + case Splitting -> handleSplitEvent(serviceUnit, data); + default -> throw new IllegalStateException("Failed to handle channel data:" + data); + } + } + + private static boolean isTransferCommand(ServiceUnitStateData data) { + if (data == null) { + return false; + } + return StringUtils.isNotEmpty(data.sourceBroker()); + } + + private static boolean isTransferCommand(Unload data) { + return data.destBroker().isPresent(); + } + + private static String getLogEventTag(ServiceUnitStateData data) { + return data == null ? "Free" : + isTransferCommand(data) ? "Transfer:" + data.state() : data.state().toString(); + } + + private void log(Throwable e, String serviceUnit, ServiceUnitStateData data, ServiceUnitStateData next) { + if (e == null) { + if (log.isDebugEnabled() || isTransferCommand(data)) { + log.info("{} handled {} event for serviceUnit:{}, cur:{}, next:{}", + lookupServiceAddress, getLogEventTag(data), serviceUnit, + data == null ? "" : data, + next == null ? "" : next); + } + } else { + log.error("{} failed to handle {} event for serviceUnit:{}, cur:{}, next:{}", + lookupServiceAddress, getLogEventTag(data), serviceUnit, + data == null ? "" : data, + next == null ? "" : next, + e); + } + } + + private void handleOwnEvent(String serviceUnit, ServiceUnitStateData data) { + var getOwnerRequest = getOwnerRequests.remove(serviceUnit); + if (getOwnerRequest != null) { + getOwnerRequest.complete(data.broker()); + } + if (isTargetBroker(data.broker())) { + log(null, serviceUnit, data, null); + } + + } + + private void handleAssignEvent(String serviceUnit, ServiceUnitStateData data) { + deferGetOwnerRequest(serviceUnit); + if (isTargetBroker(data.broker())) { + ServiceUnitStateData next = new ServiceUnitStateData( + isTransferCommand(data) ? Released : Owned, data.broker(), data.sourceBroker()); + pubAsync(serviceUnit, next) + .whenComplete((__, e) -> log(e, serviceUnit, data, next)); + } + } + + private void handleReleaseEvent(String serviceUnit, ServiceUnitStateData data) { + + if (isTargetBroker(data.sourceBroker())) { + ServiceUnitStateData next = new ServiceUnitStateData(Owned, data.broker(), data.sourceBroker()); + // TODO: when close, pass message to clients to connect to the new broker + closeServiceUnit(serviceUnit) + .thenCompose(__ -> pubAsync(serviceUnit, next)) + .whenComplete((__, e) -> log(e, serviceUnit, data, next)); + } + } + + private void handleSplitEvent(String serviceUnit, ServiceUnitStateData data) { + if (isTargetBroker(data.broker())) { + splitServiceUnit(serviceUnit) + .thenCompose(__ -> tombstoneAsync(serviceUnit)) + .whenComplete((__, e) -> log(e, serviceUnit, data, null)); + } + } + + private void handleTombstoneEvent(String serviceUnit) { + closeServiceUnit(serviceUnit) + .thenAccept(__ -> { + var request = getOwnerRequests.remove(serviceUnit); + if (request != null) { + request.completeExceptionally(new IllegalStateException("The ownership has been unloaded. " + + "No owner is found for serviceUnit: " + serviceUnit)); + } + }) + .whenComplete((__, e) -> log(e, serviceUnit, null, null)); + } + + private CompletableFuture<MessageId> pubAsync(String serviceUnit, ServiceUnitStateData data) { + CompletableFuture<MessageId> future = new CompletableFuture<>(); + try { + outstandingPubMessages.acquire(); Review Comment: The intention was to limit the `pubAsync` concurrency from this channel not to exhaust the broker threads. I removed this semaphore. ########## pulsar-broker/src/main/java/org/apache/pulsar/broker/loadbalance/extensions/channel/ServiceUnitStateChannelImpl.java: ########## @@ -0,0 +1,779 @@ +/* + * 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.channel; + +import static org.apache.pulsar.broker.loadbalance.extensions.channel.ServiceUnitState.Assigned; +import static org.apache.pulsar.broker.loadbalance.extensions.channel.ServiceUnitState.Owned; +import static org.apache.pulsar.broker.loadbalance.extensions.channel.ServiceUnitState.Released; +import static org.apache.pulsar.broker.loadbalance.extensions.channel.ServiceUnitState.Splitting; +import static org.apache.pulsar.broker.loadbalance.extensions.channel.ServiceUnitStateChannelImpl.MetadataState.Jittery; +import static org.apache.pulsar.broker.loadbalance.extensions.channel.ServiceUnitStateChannelImpl.MetadataState.Stable; +import static org.apache.pulsar.broker.loadbalance.extensions.channel.ServiceUnitStateChannelImpl.MetadataState.Unstable; +import static org.apache.pulsar.metadata.api.extended.SessionEvent.SessionLost; +import static org.apache.pulsar.metadata.api.extended.SessionEvent.SessionReestablished; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.Set; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.Executor; +import java.util.concurrent.ScheduledFuture; +import java.util.concurrent.Semaphore; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.lang3.StringUtils; +import org.apache.commons.lang3.mutable.MutableInt; +import org.apache.pulsar.broker.PulsarServerException; +import org.apache.pulsar.broker.PulsarService; +import org.apache.pulsar.broker.ServiceConfiguration; +import org.apache.pulsar.broker.loadbalance.LeaderBroker; +import org.apache.pulsar.broker.loadbalance.LeaderElectionService; +import org.apache.pulsar.broker.loadbalance.extensions.models.Split; +import org.apache.pulsar.broker.loadbalance.extensions.models.Unload; +import org.apache.pulsar.broker.loadbalance.impl.LoadManagerShared; +import org.apache.pulsar.client.admin.PulsarAdminException; +import org.apache.pulsar.client.api.MessageId; +import org.apache.pulsar.client.api.Producer; +import org.apache.pulsar.client.api.Schema; +import org.apache.pulsar.client.api.TableView; +import org.apache.pulsar.common.naming.NamespaceBundle; +import org.apache.pulsar.common.naming.NamespaceBundleSplitAlgorithm; +import org.apache.pulsar.common.naming.NamespaceName; +import org.apache.pulsar.common.naming.TopicDomain; +import org.apache.pulsar.common.util.collections.ConcurrentOpenHashMap; +import org.apache.pulsar.metadata.api.NotificationType; +import org.apache.pulsar.metadata.api.coordination.LeaderElectionState; +import org.apache.pulsar.metadata.api.extended.SessionEvent; + +@Slf4j +public class ServiceUnitStateChannelImpl implements ServiceUnitStateChannel { + public static final String TOPIC = + TopicDomain.persistent.value() + + "://" + + NamespaceName.SYSTEM_NAMESPACE + + "/service-unit-state-channel"; + private static final Schema<ServiceUnitStateData> SCHEMA = Schema.JSON(ServiceUnitStateData.class); + // TODO: define StateCompactionStrategy + private static final long COMPACTION_THRESHOLD = 5 * 1024 * 1024; // 5mb + private static final long MAX_IN_FLIGHT_STATE_WAITING_TIME_IN_MILLIS = 30 * 1000; // 30sec + public static final long MAX_CLEAN_UP_DELAY_TIME_IN_SECS = 3 * 60; // 3 mins + private static final long MIN_CLEAN_UP_DELAY_TIME_IN_SECS = 0; // 0 secs to clean immediately + private static final int MAX_OUTSTANDING_PUB_MESSAGES = 500; + private final PulsarService pulsar; + private TableView<ServiceUnitStateData> tableview; + private Producer<ServiceUnitStateData> producer; + private final ConcurrentOpenHashMap<String, CompletableFuture<String>> getOwnerRequests; + private String lookupServiceAddress; + private LeaderElectionService leaderElectionService; + // TODO: define BrokerRegistry + private SessionEvent lastMetadataSessionEvent = SessionReestablished; + private long lastMetadataSessionEventTimestamp = 0; + private Semaphore outstandingPubMessages; + + private Semaphore outstandingCleanupTombstoneMessages; + private ScheduledFuture<?> cleanupTasks; + private long inFlightStateWaitingTimeInMillis; + private long maxCleanupDelayTimeInSecs; + private long minCleanupDelayTimeInSecs; + + private ConcurrentOpenHashMap<String, CompletableFuture<Void>> cleanupJobs; + + // cleanup metrics + private long totalCleanupCnt = 0; + private long totalBrokerCleanupTombstoneCnt = 0; + private long totalServiceUnitCleanupTombstoneCnt = 0; + private long totalServiceUnitCleanupErrorCnt = 0; + private long totalCleanupScheduledCnt = 0; + private long totalCleanupIgnoredCnt = 0; + private long totalCleanupCancelledCnt = 0; + + + enum MetadataState { + Stable, + Jittery, + Unstable + } + + public ServiceUnitStateChannelImpl(PulsarService pulsar) { + this.pulsar = pulsar; + ServiceConfiguration conf = pulsar.getConfiguration(); + this.lookupServiceAddress = pulsar.getAdvertisedAddress() + ":" + + (conf.getWebServicePort().isPresent() ? conf.getWebServicePort().get() + : conf.getWebServicePortTls().get()); + this.outstandingPubMessages = new Semaphore(MAX_OUTSTANDING_PUB_MESSAGES); + this.outstandingCleanupTombstoneMessages = new Semaphore(MAX_OUTSTANDING_PUB_MESSAGES); + this.getOwnerRequests = ConcurrentOpenHashMap.<String, + CompletableFuture<String>>newBuilder() + .build(); + this.cleanupJobs = + ConcurrentOpenHashMap.<String, CompletableFuture<Void>>newBuilder() + .build(); + this.inFlightStateWaitingTimeInMillis = MAX_IN_FLIGHT_STATE_WAITING_TIME_IN_MILLIS; + this.maxCleanupDelayTimeInSecs = MAX_CLEAN_UP_DELAY_TIME_IN_SECS; + this.minCleanupDelayTimeInSecs = MIN_CLEAN_UP_DELAY_TIME_IN_SECS; + } + + public void start() throws PulsarServerException { + + try { + if (leaderElectionService != null) { + leaderElectionService.close(); + log.debug("Closed the channel leader election service."); + } + this.leaderElectionService = new LeaderElectionService( + pulsar.getCoordinationService(), pulsar.getSafeWebServiceAddress(), + state -> { + if (state == LeaderElectionState.Leading) { + log.debug("This broker:{} was elected as the leader." + + "Current channel leader is {}", + lookupServiceAddress, + leaderElectionService.getCurrentLeader()); + } else { + if (leaderElectionService != null) { + log.debug("This broker:{} is a follower. " + + "Current channel leader is {}", + lookupServiceAddress, + leaderElectionService.getCurrentLeader()); + } + } + }); + leaderElectionService.start(); + log.debug("Successfully started the channel leader election service."); + + if (producer != null) { + producer.close(); + log.debug("Closed the channel producer."); + } + producer = pulsar.getClient().newProducer(SCHEMA) + .enableBatching(true) + .topic(TOPIC) + .create(); + + log.debug("Successfully started the channel producer."); + + if (tableview != null) { + tableview.close(); + log.debug("Closed the channel tableview."); + } + tableview = pulsar.getClient().newTableViewBuilder(SCHEMA) + .topic(TOPIC) + // TODO: enable CompactionStrategy + .create(); + // TODO: schedule listen instead of foreachAndListen + tableview.forEachAndListen((key, value) -> handle(key, value)); + log.debug("Successfully started the channel tableview."); + + // TODO: schedule cleanupTasks by brokerRegistry + pulsar.getLocalMetadataStore().registerSessionListener(this::handleMetadataSessionEvent); + log.debug("Successfully registered the handleMetadataSessionEvent"); + + log.info("Successfully started the channel."); + } catch (Exception e) { + String msg = "Failed to start the channel."; + log.error(msg, e); + throw new PulsarServerException(msg, e); + } + } + + + public void close() throws PulsarServerException { + try { + if (leaderElectionService != null) { + leaderElectionService.close(); + leaderElectionService = null; + log.debug("Successfully closed the channel leader election service."); + } + + if (tableview != null) { + tableview.close(); + tableview = null; + log.debug("Successfully closed the channel tableview."); + } + + if (producer != null) { + producer.close(); + producer = null; + log.info("Successfully closed the channel producer."); + } + + // TODO: clean brokerRegistry + + if (cleanupTasks != null) { + cleanupTasks.cancel(true); + cleanupTasks = null; + log.info("Successfully cancelled the cleanup tasks"); + } + + log.info("Successfully closed the channel."); + + } catch (Exception e) { + String msg = "Failed to close the channel."; + log.error(msg, e); + throw new PulsarServerException(msg, e); + } + } + + public void scheduleCompaction() throws PulsarServerException { + try { + Long threshold = pulsar.getAdminClient().topicPolicies() + .getCompactionThreshold(TOPIC); + if (threshold == null || threshold == 0) { + pulsar.getAdminClient().topicPolicies() + .setCompactionThreshold(TOPIC, COMPACTION_THRESHOLD); + log.info("Scheduled compaction on topic:{}, threshold:{} bytes", TOPIC, COMPACTION_THRESHOLD); + } else { + log.info("Already set compaction on topic:{}, threshold:{} bytes", TOPIC, COMPACTION_THRESHOLD); + } + } catch (PulsarAdminException e) { + throw new PulsarServerException("Failed to schedule compaction.", e); + } + } + + public String getChannelOwner() { + CompletableFuture<Optional<LeaderBroker>> future = leaderElectionService.readCurrentLeader(); Review Comment: - Added a private variable `volatile boolean isActive` and set this flag in start() and close(). - Made start() and close() synchronized. - Added validateChannel() to validate concurrent access to `leaderElectionService, producer, and tableview` while `isActive=false`. - Added a UT to cover this access logic. ########## pulsar-broker/src/main/java/org/apache/pulsar/broker/loadbalance/extensions/channel/ServiceUnitStateChannelImpl.java: ########## @@ -0,0 +1,779 @@ +/* + * 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.channel; + +import static org.apache.pulsar.broker.loadbalance.extensions.channel.ServiceUnitState.Assigned; +import static org.apache.pulsar.broker.loadbalance.extensions.channel.ServiceUnitState.Owned; +import static org.apache.pulsar.broker.loadbalance.extensions.channel.ServiceUnitState.Released; +import static org.apache.pulsar.broker.loadbalance.extensions.channel.ServiceUnitState.Splitting; +import static org.apache.pulsar.broker.loadbalance.extensions.channel.ServiceUnitStateChannelImpl.MetadataState.Jittery; +import static org.apache.pulsar.broker.loadbalance.extensions.channel.ServiceUnitStateChannelImpl.MetadataState.Stable; +import static org.apache.pulsar.broker.loadbalance.extensions.channel.ServiceUnitStateChannelImpl.MetadataState.Unstable; +import static org.apache.pulsar.metadata.api.extended.SessionEvent.SessionLost; +import static org.apache.pulsar.metadata.api.extended.SessionEvent.SessionReestablished; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.Set; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.Executor; +import java.util.concurrent.ScheduledFuture; +import java.util.concurrent.Semaphore; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.lang3.StringUtils; +import org.apache.commons.lang3.mutable.MutableInt; +import org.apache.pulsar.broker.PulsarServerException; +import org.apache.pulsar.broker.PulsarService; +import org.apache.pulsar.broker.ServiceConfiguration; +import org.apache.pulsar.broker.loadbalance.LeaderBroker; +import org.apache.pulsar.broker.loadbalance.LeaderElectionService; +import org.apache.pulsar.broker.loadbalance.extensions.models.Split; +import org.apache.pulsar.broker.loadbalance.extensions.models.Unload; +import org.apache.pulsar.broker.loadbalance.impl.LoadManagerShared; +import org.apache.pulsar.client.admin.PulsarAdminException; +import org.apache.pulsar.client.api.MessageId; +import org.apache.pulsar.client.api.Producer; +import org.apache.pulsar.client.api.Schema; +import org.apache.pulsar.client.api.TableView; +import org.apache.pulsar.common.naming.NamespaceBundle; +import org.apache.pulsar.common.naming.NamespaceBundleSplitAlgorithm; +import org.apache.pulsar.common.naming.NamespaceName; +import org.apache.pulsar.common.naming.TopicDomain; +import org.apache.pulsar.common.util.collections.ConcurrentOpenHashMap; +import org.apache.pulsar.metadata.api.NotificationType; +import org.apache.pulsar.metadata.api.coordination.LeaderElectionState; +import org.apache.pulsar.metadata.api.extended.SessionEvent; + +@Slf4j +public class ServiceUnitStateChannelImpl implements ServiceUnitStateChannel { + public static final String TOPIC = + TopicDomain.persistent.value() + + "://" + + NamespaceName.SYSTEM_NAMESPACE + + "/service-unit-state-channel"; + private static final Schema<ServiceUnitStateData> SCHEMA = Schema.JSON(ServiceUnitStateData.class); + // TODO: define StateCompactionStrategy + private static final long COMPACTION_THRESHOLD = 5 * 1024 * 1024; // 5mb + private static final long MAX_IN_FLIGHT_STATE_WAITING_TIME_IN_MILLIS = 30 * 1000; // 30sec + public static final long MAX_CLEAN_UP_DELAY_TIME_IN_SECS = 3 * 60; // 3 mins + private static final long MIN_CLEAN_UP_DELAY_TIME_IN_SECS = 0; // 0 secs to clean immediately + private static final int MAX_OUTSTANDING_PUB_MESSAGES = 500; + private final PulsarService pulsar; + private TableView<ServiceUnitStateData> tableview; + private Producer<ServiceUnitStateData> producer; + private final ConcurrentOpenHashMap<String, CompletableFuture<String>> getOwnerRequests; + private String lookupServiceAddress; + private LeaderElectionService leaderElectionService; + // TODO: define BrokerRegistry + private SessionEvent lastMetadataSessionEvent = SessionReestablished; + private long lastMetadataSessionEventTimestamp = 0; + private Semaphore outstandingPubMessages; + + private Semaphore outstandingCleanupTombstoneMessages; + private ScheduledFuture<?> cleanupTasks; + private long inFlightStateWaitingTimeInMillis; + private long maxCleanupDelayTimeInSecs; + private long minCleanupDelayTimeInSecs; + + private ConcurrentOpenHashMap<String, CompletableFuture<Void>> cleanupJobs; + + // cleanup metrics + private long totalCleanupCnt = 0; + private long totalBrokerCleanupTombstoneCnt = 0; + private long totalServiceUnitCleanupTombstoneCnt = 0; + private long totalServiceUnitCleanupErrorCnt = 0; + private long totalCleanupScheduledCnt = 0; + private long totalCleanupIgnoredCnt = 0; + private long totalCleanupCancelledCnt = 0; + + + enum MetadataState { + Stable, + Jittery, + Unstable + } + + public ServiceUnitStateChannelImpl(PulsarService pulsar) { + this.pulsar = pulsar; + ServiceConfiguration conf = pulsar.getConfiguration(); + this.lookupServiceAddress = pulsar.getAdvertisedAddress() + ":" + + (conf.getWebServicePort().isPresent() ? conf.getWebServicePort().get() + : conf.getWebServicePortTls().get()); + this.outstandingPubMessages = new Semaphore(MAX_OUTSTANDING_PUB_MESSAGES); + this.outstandingCleanupTombstoneMessages = new Semaphore(MAX_OUTSTANDING_PUB_MESSAGES); + this.getOwnerRequests = ConcurrentOpenHashMap.<String, + CompletableFuture<String>>newBuilder() + .build(); + this.cleanupJobs = + ConcurrentOpenHashMap.<String, CompletableFuture<Void>>newBuilder() + .build(); + this.inFlightStateWaitingTimeInMillis = MAX_IN_FLIGHT_STATE_WAITING_TIME_IN_MILLIS; + this.maxCleanupDelayTimeInSecs = MAX_CLEAN_UP_DELAY_TIME_IN_SECS; + this.minCleanupDelayTimeInSecs = MIN_CLEAN_UP_DELAY_TIME_IN_SECS; + } + + public void start() throws PulsarServerException { + + try { + if (leaderElectionService != null) { + leaderElectionService.close(); + log.debug("Closed the channel leader election service."); + } + this.leaderElectionService = new LeaderElectionService( + pulsar.getCoordinationService(), pulsar.getSafeWebServiceAddress(), + state -> { + if (state == LeaderElectionState.Leading) { + log.debug("This broker:{} was elected as the leader." + + "Current channel leader is {}", + lookupServiceAddress, + leaderElectionService.getCurrentLeader()); + } else { + if (leaderElectionService != null) { + log.debug("This broker:{} is a follower. " + + "Current channel leader is {}", + lookupServiceAddress, + leaderElectionService.getCurrentLeader()); + } + } + }); + leaderElectionService.start(); + log.debug("Successfully started the channel leader election service."); + + if (producer != null) { + producer.close(); + log.debug("Closed the channel producer."); + } + producer = pulsar.getClient().newProducer(SCHEMA) + .enableBatching(true) + .topic(TOPIC) + .create(); + + log.debug("Successfully started the channel producer."); + + if (tableview != null) { + tableview.close(); + log.debug("Closed the channel tableview."); + } + tableview = pulsar.getClient().newTableViewBuilder(SCHEMA) + .topic(TOPIC) + // TODO: enable CompactionStrategy + .create(); + // TODO: schedule listen instead of foreachAndListen + tableview.forEachAndListen((key, value) -> handle(key, value)); + log.debug("Successfully started the channel tableview."); + + // TODO: schedule cleanupTasks by brokerRegistry + pulsar.getLocalMetadataStore().registerSessionListener(this::handleMetadataSessionEvent); + log.debug("Successfully registered the handleMetadataSessionEvent"); + + log.info("Successfully started the channel."); + } catch (Exception e) { + String msg = "Failed to start the channel."; + log.error(msg, e); + throw new PulsarServerException(msg, e); + } + } + + + public void close() throws PulsarServerException { + try { + if (leaderElectionService != null) { + leaderElectionService.close(); + leaderElectionService = null; + log.debug("Successfully closed the channel leader election service."); + } + + if (tableview != null) { + tableview.close(); + tableview = null; + log.debug("Successfully closed the channel tableview."); + } + + if (producer != null) { + producer.close(); + producer = null; + log.info("Successfully closed the channel producer."); + } + + // TODO: clean brokerRegistry + + if (cleanupTasks != null) { + cleanupTasks.cancel(true); + cleanupTasks = null; + log.info("Successfully cancelled the cleanup tasks"); + } + + log.info("Successfully closed the channel."); + + } catch (Exception e) { + String msg = "Failed to close the channel."; + log.error(msg, e); + throw new PulsarServerException(msg, e); + } + } + + public void scheduleCompaction() throws PulsarServerException { + try { + Long threshold = pulsar.getAdminClient().topicPolicies() + .getCompactionThreshold(TOPIC); + if (threshold == null || threshold == 0) { + pulsar.getAdminClient().topicPolicies() + .setCompactionThreshold(TOPIC, COMPACTION_THRESHOLD); + log.info("Scheduled compaction on topic:{}, threshold:{} bytes", TOPIC, COMPACTION_THRESHOLD); + } else { + log.info("Already set compaction on topic:{}, threshold:{} bytes", TOPIC, COMPACTION_THRESHOLD); + } + } catch (PulsarAdminException e) { + throw new PulsarServerException("Failed to schedule compaction.", e); + } + } + + public String getChannelOwner() { + CompletableFuture<Optional<LeaderBroker>> future = leaderElectionService.readCurrentLeader(); + if (!future.isDone()) { + return null; + } + Optional<LeaderBroker> leader = future.join(); + if (leader.isEmpty()) { + return null; + } + //expecting http://broker-xyz:port + String broker = leader.get().getServiceUrl(); + broker = broker.substring(broker.lastIndexOf('/') + 1); Review Comment: Agreed, but I assume this util func is not required in this PR. I added a TODO comment here. `// TODO: discard this protocol prefix removal by a util func that returns lookupServiceAddress(serviceUrl)` ########## pulsar-broker/src/main/java/org/apache/pulsar/broker/loadbalance/extensions/channel/ServiceUnitStateChannelImpl.java: ########## @@ -0,0 +1,779 @@ +/* + * 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.channel; + +import static org.apache.pulsar.broker.loadbalance.extensions.channel.ServiceUnitState.Assigned; +import static org.apache.pulsar.broker.loadbalance.extensions.channel.ServiceUnitState.Owned; +import static org.apache.pulsar.broker.loadbalance.extensions.channel.ServiceUnitState.Released; +import static org.apache.pulsar.broker.loadbalance.extensions.channel.ServiceUnitState.Splitting; +import static org.apache.pulsar.broker.loadbalance.extensions.channel.ServiceUnitStateChannelImpl.MetadataState.Jittery; +import static org.apache.pulsar.broker.loadbalance.extensions.channel.ServiceUnitStateChannelImpl.MetadataState.Stable; +import static org.apache.pulsar.broker.loadbalance.extensions.channel.ServiceUnitStateChannelImpl.MetadataState.Unstable; +import static org.apache.pulsar.metadata.api.extended.SessionEvent.SessionLost; +import static org.apache.pulsar.metadata.api.extended.SessionEvent.SessionReestablished; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.Set; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.Executor; +import java.util.concurrent.ScheduledFuture; +import java.util.concurrent.Semaphore; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.lang3.StringUtils; +import org.apache.commons.lang3.mutable.MutableInt; +import org.apache.pulsar.broker.PulsarServerException; +import org.apache.pulsar.broker.PulsarService; +import org.apache.pulsar.broker.ServiceConfiguration; +import org.apache.pulsar.broker.loadbalance.LeaderBroker; +import org.apache.pulsar.broker.loadbalance.LeaderElectionService; +import org.apache.pulsar.broker.loadbalance.extensions.models.Split; +import org.apache.pulsar.broker.loadbalance.extensions.models.Unload; +import org.apache.pulsar.broker.loadbalance.impl.LoadManagerShared; +import org.apache.pulsar.client.admin.PulsarAdminException; +import org.apache.pulsar.client.api.MessageId; +import org.apache.pulsar.client.api.Producer; +import org.apache.pulsar.client.api.Schema; +import org.apache.pulsar.client.api.TableView; +import org.apache.pulsar.common.naming.NamespaceBundle; +import org.apache.pulsar.common.naming.NamespaceBundleSplitAlgorithm; +import org.apache.pulsar.common.naming.NamespaceName; +import org.apache.pulsar.common.naming.TopicDomain; +import org.apache.pulsar.common.util.collections.ConcurrentOpenHashMap; +import org.apache.pulsar.metadata.api.NotificationType; +import org.apache.pulsar.metadata.api.coordination.LeaderElectionState; +import org.apache.pulsar.metadata.api.extended.SessionEvent; + +@Slf4j +public class ServiceUnitStateChannelImpl implements ServiceUnitStateChannel { + public static final String TOPIC = + TopicDomain.persistent.value() + + "://" + + NamespaceName.SYSTEM_NAMESPACE + + "/service-unit-state-channel"; + private static final Schema<ServiceUnitStateData> SCHEMA = Schema.JSON(ServiceUnitStateData.class); + // TODO: define StateCompactionStrategy + private static final long COMPACTION_THRESHOLD = 5 * 1024 * 1024; // 5mb + private static final long MAX_IN_FLIGHT_STATE_WAITING_TIME_IN_MILLIS = 30 * 1000; // 30sec + public static final long MAX_CLEAN_UP_DELAY_TIME_IN_SECS = 3 * 60; // 3 mins + private static final long MIN_CLEAN_UP_DELAY_TIME_IN_SECS = 0; // 0 secs to clean immediately + private static final int MAX_OUTSTANDING_PUB_MESSAGES = 500; + private final PulsarService pulsar; + private TableView<ServiceUnitStateData> tableview; + private Producer<ServiceUnitStateData> producer; + private final ConcurrentOpenHashMap<String, CompletableFuture<String>> getOwnerRequests; + private String lookupServiceAddress; + private LeaderElectionService leaderElectionService; + // TODO: define BrokerRegistry + private SessionEvent lastMetadataSessionEvent = SessionReestablished; + private long lastMetadataSessionEventTimestamp = 0; + private Semaphore outstandingPubMessages; + + private Semaphore outstandingCleanupTombstoneMessages; + private ScheduledFuture<?> cleanupTasks; + private long inFlightStateWaitingTimeInMillis; + private long maxCleanupDelayTimeInSecs; + private long minCleanupDelayTimeInSecs; + + private ConcurrentOpenHashMap<String, CompletableFuture<Void>> cleanupJobs; + + // cleanup metrics + private long totalCleanupCnt = 0; + private long totalBrokerCleanupTombstoneCnt = 0; + private long totalServiceUnitCleanupTombstoneCnt = 0; + private long totalServiceUnitCleanupErrorCnt = 0; + private long totalCleanupScheduledCnt = 0; + private long totalCleanupIgnoredCnt = 0; + private long totalCleanupCancelledCnt = 0; + + + enum MetadataState { + Stable, + Jittery, + Unstable + } + + public ServiceUnitStateChannelImpl(PulsarService pulsar) { + this.pulsar = pulsar; + ServiceConfiguration conf = pulsar.getConfiguration(); + this.lookupServiceAddress = pulsar.getAdvertisedAddress() + ":" + + (conf.getWebServicePort().isPresent() ? conf.getWebServicePort().get() + : conf.getWebServicePortTls().get()); + this.outstandingPubMessages = new Semaphore(MAX_OUTSTANDING_PUB_MESSAGES); + this.outstandingCleanupTombstoneMessages = new Semaphore(MAX_OUTSTANDING_PUB_MESSAGES); + this.getOwnerRequests = ConcurrentOpenHashMap.<String, + CompletableFuture<String>>newBuilder() + .build(); + this.cleanupJobs = + ConcurrentOpenHashMap.<String, CompletableFuture<Void>>newBuilder() + .build(); + this.inFlightStateWaitingTimeInMillis = MAX_IN_FLIGHT_STATE_WAITING_TIME_IN_MILLIS; + this.maxCleanupDelayTimeInSecs = MAX_CLEAN_UP_DELAY_TIME_IN_SECS; + this.minCleanupDelayTimeInSecs = MIN_CLEAN_UP_DELAY_TIME_IN_SECS; + } + + public void start() throws PulsarServerException { + + try { + if (leaderElectionService != null) { + leaderElectionService.close(); + log.debug("Closed the channel leader election service."); + } + this.leaderElectionService = new LeaderElectionService( + pulsar.getCoordinationService(), pulsar.getSafeWebServiceAddress(), + state -> { + if (state == LeaderElectionState.Leading) { + log.debug("This broker:{} was elected as the leader." + + "Current channel leader is {}", + lookupServiceAddress, + leaderElectionService.getCurrentLeader()); + } else { + if (leaderElectionService != null) { + log.debug("This broker:{} is a follower. " + + "Current channel leader is {}", + lookupServiceAddress, + leaderElectionService.getCurrentLeader()); + } + } + }); + leaderElectionService.start(); + log.debug("Successfully started the channel leader election service."); + + if (producer != null) { + producer.close(); + log.debug("Closed the channel producer."); + } + producer = pulsar.getClient().newProducer(SCHEMA) + .enableBatching(true) + .topic(TOPIC) + .create(); + + log.debug("Successfully started the channel producer."); + + if (tableview != null) { + tableview.close(); + log.debug("Closed the channel tableview."); + } + tableview = pulsar.getClient().newTableViewBuilder(SCHEMA) + .topic(TOPIC) + // TODO: enable CompactionStrategy + .create(); + // TODO: schedule listen instead of foreachAndListen + tableview.forEachAndListen((key, value) -> handle(key, value)); + log.debug("Successfully started the channel tableview."); + + // TODO: schedule cleanupTasks by brokerRegistry + pulsar.getLocalMetadataStore().registerSessionListener(this::handleMetadataSessionEvent); + log.debug("Successfully registered the handleMetadataSessionEvent"); + + log.info("Successfully started the channel."); + } catch (Exception e) { + String msg = "Failed to start the channel."; + log.error(msg, e); + throw new PulsarServerException(msg, e); + } + } + + + public void close() throws PulsarServerException { + try { + if (leaderElectionService != null) { + leaderElectionService.close(); + leaderElectionService = null; + log.debug("Successfully closed the channel leader election service."); + } + + if (tableview != null) { + tableview.close(); + tableview = null; + log.debug("Successfully closed the channel tableview."); + } + + if (producer != null) { + producer.close(); + producer = null; + log.info("Successfully closed the channel producer."); + } + + // TODO: clean brokerRegistry + + if (cleanupTasks != null) { + cleanupTasks.cancel(true); + cleanupTasks = null; + log.info("Successfully cancelled the cleanup tasks"); + } + + log.info("Successfully closed the channel."); + + } catch (Exception e) { + String msg = "Failed to close the channel."; + log.error(msg, e); + throw new PulsarServerException(msg, e); + } + } + + public void scheduleCompaction() throws PulsarServerException { + try { + Long threshold = pulsar.getAdminClient().topicPolicies() + .getCompactionThreshold(TOPIC); + if (threshold == null || threshold == 0) { + pulsar.getAdminClient().topicPolicies() + .setCompactionThreshold(TOPIC, COMPACTION_THRESHOLD); + log.info("Scheduled compaction on topic:{}, threshold:{} bytes", TOPIC, COMPACTION_THRESHOLD); + } else { + log.info("Already set compaction on topic:{}, threshold:{} bytes", TOPIC, COMPACTION_THRESHOLD); + } + } catch (PulsarAdminException e) { + throw new PulsarServerException("Failed to schedule compaction.", e); + } + } + + public String getChannelOwner() { + CompletableFuture<Optional<LeaderBroker>> future = leaderElectionService.readCurrentLeader(); + if (!future.isDone()) { + return null; + } + Optional<LeaderBroker> leader = future.join(); + if (leader.isEmpty()) { + return null; + } + //expecting http://broker-xyz:port + String broker = leader.get().getServiceUrl(); + broker = broker.substring(broker.lastIndexOf('/') + 1); + return broker; + } + + public boolean isChannelOwner() { + return isTargetBroker(getChannelOwner()); + } + + public CompletableFuture<String> getOwnerAsync(String serviceUnit) { + + ServiceUnitStateData data = tableview.get(serviceUnit); + if (data == null) { + return null; + } + switch (data.state()) { + case Owned, Splitting -> { + return CompletableFuture.completedFuture(data.broker()); + } + case Assigned, Released -> { + return deferGetOwnerRequest(serviceUnit); + } + default -> { + return null; + } + } + } + + public CompletableFuture<String> publishAssignEventAsync(String serviceUnit, String broker) { + CompletableFuture<String> getOwnerRequest = deferGetOwnerRequest(serviceUnit); + pubAsync(serviceUnit, new ServiceUnitStateData(Assigned, broker)) + .whenComplete((__, ex) -> { + if (ex != null) { + getOwnerRequests.remove(serviceUnit); + if (!getOwnerRequest.isCompletedExceptionally()) { + getOwnerRequest.completeExceptionally(ex); + } + } + }); + + return getOwnerRequest; + } + + public CompletableFuture<Void> publishUnloadEventAsync(Unload unload) { + String serviceUnit = unload.serviceUnit(); + if (isTransferCommand(unload)) { + ServiceUnitStateData next = new ServiceUnitStateData(Assigned, + unload.destBroker().get(), unload.sourceBroker()); + return pubAsync(serviceUnit, next).thenAccept(__ -> { + }); + } + return tombstoneAsync(serviceUnit).thenAccept(__ -> { + }); + } + + public CompletableFuture<Void> publishSplitEventAsync(Split split) { + String serviceUnit = split.serviceUnit(); + ServiceUnitStateData data = tableview.get(serviceUnit); + ServiceUnitStateData next = new ServiceUnitStateData(Splitting, data.broker()); + return pubAsync(serviceUnit, next).thenAccept(__ -> { + }); + } + + private void handle(String serviceUnit, ServiceUnitStateData data) { + if (log.isDebugEnabled()) { + log.info("{} received a handle request for serviceUnit:{}, data:{}", + lookupServiceAddress, serviceUnit, data); + } + + if (data == null) { + handleTombstoneEvent(serviceUnit); + return; + } + + // TODO : Add state validation + switch (data.state()) { + case Owned -> handleOwnEvent(serviceUnit, data); + case Assigned -> handleAssignEvent(serviceUnit, data); + case Released -> handleReleaseEvent(serviceUnit, data); + case Splitting -> handleSplitEvent(serviceUnit, data); + default -> throw new IllegalStateException("Failed to handle channel data:" + data); + } + } + + private static boolean isTransferCommand(ServiceUnitStateData data) { + if (data == null) { + return false; + } + return StringUtils.isNotEmpty(data.sourceBroker()); + } + + private static boolean isTransferCommand(Unload data) { + return data.destBroker().isPresent(); + } + + private static String getLogEventTag(ServiceUnitStateData data) { + return data == null ? "Free" : + isTransferCommand(data) ? "Transfer:" + data.state() : data.state().toString(); + } + + private void log(Throwable e, String serviceUnit, ServiceUnitStateData data, ServiceUnitStateData next) { + if (e == null) { + if (log.isDebugEnabled() || isTransferCommand(data)) { + log.info("{} handled {} event for serviceUnit:{}, cur:{}, next:{}", + lookupServiceAddress, getLogEventTag(data), serviceUnit, + data == null ? "" : data, + next == null ? "" : next); + } + } else { + log.error("{} failed to handle {} event for serviceUnit:{}, cur:{}, next:{}", + lookupServiceAddress, getLogEventTag(data), serviceUnit, + data == null ? "" : data, + next == null ? "" : next, + e); + } + } + + private void handleOwnEvent(String serviceUnit, ServiceUnitStateData data) { + var getOwnerRequest = getOwnerRequests.remove(serviceUnit); + if (getOwnerRequest != null) { + getOwnerRequest.complete(data.broker()); + } + if (isTargetBroker(data.broker())) { + log(null, serviceUnit, data, null); + } + + } + + private void handleAssignEvent(String serviceUnit, ServiceUnitStateData data) { + deferGetOwnerRequest(serviceUnit); + if (isTargetBroker(data.broker())) { + ServiceUnitStateData next = new ServiceUnitStateData( + isTransferCommand(data) ? Released : Owned, data.broker(), data.sourceBroker()); + pubAsync(serviceUnit, next) + .whenComplete((__, e) -> log(e, serviceUnit, data, next)); + } + } + + private void handleReleaseEvent(String serviceUnit, ServiceUnitStateData data) { + + if (isTargetBroker(data.sourceBroker())) { + ServiceUnitStateData next = new ServiceUnitStateData(Owned, data.broker(), data.sourceBroker()); + // TODO: when close, pass message to clients to connect to the new broker + closeServiceUnit(serviceUnit) + .thenCompose(__ -> pubAsync(serviceUnit, next)) + .whenComplete((__, e) -> log(e, serviceUnit, data, next)); + } + } + + private void handleSplitEvent(String serviceUnit, ServiceUnitStateData data) { + if (isTargetBroker(data.broker())) { + splitServiceUnit(serviceUnit) + .thenCompose(__ -> tombstoneAsync(serviceUnit)) + .whenComplete((__, e) -> log(e, serviceUnit, data, null)); + } + } + + private void handleTombstoneEvent(String serviceUnit) { + closeServiceUnit(serviceUnit) + .thenAccept(__ -> { + var request = getOwnerRequests.remove(serviceUnit); + if (request != null) { + request.completeExceptionally(new IllegalStateException("The ownership has been unloaded. " + + "No owner is found for serviceUnit: " + serviceUnit)); + } + }) + .whenComplete((__, e) -> log(e, serviceUnit, null, null)); + } + + private CompletableFuture<MessageId> pubAsync(String serviceUnit, ServiceUnitStateData data) { + CompletableFuture<MessageId> future = new CompletableFuture<>(); + try { + outstandingPubMessages.acquire(); + } catch (InterruptedException e) { + log.warn("Interrupted while acquiring semaphore to publish a message for serviceUnit:{}, data:{}", + serviceUnit, data); + future.completeExceptionally(e); + return future; + } + producer.newMessage() + .key(serviceUnit) + .value(data) + .sendAsync() + .whenComplete((messageId, e) -> { + outstandingPubMessages.release(); + if (e != null) { + future.completeExceptionally(e); + } else { + future.complete(messageId); + } + }); + return future; + } + + private CompletableFuture<MessageId> tombstoneAsync(String serviceUnit) { + return pubAsync(serviceUnit, null); + } + + private boolean isTargetBroker(String broker) { + if (broker == null) { + return false; + } + // TODO: remove broker port from the input broker Review Comment: Removed the comment. -- 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]
