Search in sources :

Example 1 with CoordinationService

use of org.apache.pulsar.metadata.api.coordination.CoordinationService in project pulsar by apache.

the class PulsarService method startLeaderElectionService.

protected void startLeaderElectionService() {
    this.leaderElectionService = new LeaderElectionService(coordinationService, getSafeWebServiceAddress(), state -> {
        if (state == LeaderElectionState.Leading) {
            LOG.info("This broker was elected leader");
            if (getConfiguration().isLoadBalancerEnabled()) {
                long loadSheddingInterval = TimeUnit.MINUTES.toMillis(getConfiguration().getLoadBalancerSheddingIntervalMinutes());
                long resourceQuotaUpdateInterval = TimeUnit.MINUTES.toMillis(getConfiguration().getLoadBalancerResourceQuotaUpdateIntervalMinutes());
                if (loadSheddingTask != null) {
                    loadSheddingTask.cancel(false);
                }
                if (loadResourceQuotaTask != null) {
                    loadResourceQuotaTask.cancel(false);
                }
                loadSheddingTask = loadManagerExecutor.scheduleAtFixedRate(new LoadSheddingTask(loadManager), loadSheddingInterval, loadSheddingInterval, TimeUnit.MILLISECONDS);
                loadResourceQuotaTask = loadManagerExecutor.scheduleAtFixedRate(new LoadResourceQuotaUpdaterTask(loadManager), resourceQuotaUpdateInterval, resourceQuotaUpdateInterval, TimeUnit.MILLISECONDS);
            }
        } else {
            if (leaderElectionService != null) {
                LOG.info("This broker is a follower. Current leader is {}", leaderElectionService.getCurrentLeader());
            }
            if (loadSheddingTask != null) {
                loadSheddingTask.cancel(false);
                loadSheddingTask = null;
            }
            if (loadResourceQuotaTask != null) {
                loadResourceQuotaTask.cancel(false);
                loadResourceQuotaTask = null;
            }
        }
    });
    leaderElectionService.start();
}
Also used : ManagedLedgerStorage(org.apache.pulsar.broker.storage.ManagedLedgerStorage) ClusterDataImpl(org.apache.pulsar.common.policies.data.ClusterDataImpl) Topic(org.apache.pulsar.broker.service.Topic) PulsarClientImpl(org.apache.pulsar.client.impl.PulsarClientImpl) PulsarConfigurationLoader(org.apache.pulsar.common.configuration.PulsarConfigurationLoader) AdditionalServlets(org.apache.pulsar.broker.web.plugin.servlet.AdditionalServlets) DefaultPackagesStorageConfiguration(org.apache.pulsar.packages.management.core.impl.DefaultPackagesStorageConfiguration) OffloadersCache(org.apache.bookkeeper.mledger.offload.OffloadersCache) MetadataStore(org.apache.pulsar.metadata.api.MetadataStore) LedgerOffloader(org.apache.bookkeeper.mledger.LedgerOffloader) LoadManager(org.apache.pulsar.broker.loadbalance.LoadManager) StringUtils(org.apache.commons.lang3.StringUtils) TransactionMetadataStoreProvider(org.apache.pulsar.transaction.coordinator.TransactionMetadataStoreProvider) SchemaStorage(org.apache.pulsar.common.protocol.schema.SchemaStorage) ExecutorProvider(org.apache.pulsar.client.util.ExecutorProvider) ThreadDumpUtil(org.apache.pulsar.common.util.ThreadDumpUtil) Duration(java.time.Duration) Map(java.util.Map) AdditionalServletWithPulsarService(org.apache.pulsar.broker.web.plugin.servlet.AdditionalServletWithPulsarService) BrokerInterceptor(org.apache.pulsar.broker.intercept.BrokerInterceptor) VipStatus(org.apache.pulsar.common.configuration.VipStatus) GracefulExecutorServicesShutdown(org.apache.pulsar.broker.service.GracefulExecutorServicesShutdown) SocketChannel(io.netty.channel.socket.SocketChannel) MetadataStoreException(org.apache.pulsar.metadata.api.MetadataStoreException) ResourceGroupService(org.apache.pulsar.broker.resourcegroup.ResourceGroupService) CancellationException(java.util.concurrent.CancellationException) TopicPoliciesService(org.apache.pulsar.broker.service.TopicPoliciesService) ServletHolder(org.eclipse.jetty.servlet.ServletHolder) WebSocketConsumerServlet(org.apache.pulsar.websocket.WebSocketConsumerServlet) BrokerService(org.apache.pulsar.broker.service.BrokerService) WorkerConfig(org.apache.pulsar.functions.worker.WorkerConfig) BookKeeper(org.apache.bookkeeper.client.BookKeeper) Executors(java.util.concurrent.Executors) WebSocketServlet(org.eclipse.jetty.websocket.servlet.WebSocketServlet) StringUtils.isNotBlank(org.apache.commons.lang3.StringUtils.isNotBlank) AdditionalServlet(org.apache.pulsar.broker.web.plugin.servlet.AdditionalServlet) SessionEvent(org.apache.pulsar.metadata.api.extended.SessionEvent) LoadSheddingTask(org.apache.pulsar.broker.loadbalance.LoadSheddingTask) MetricsGenerator(org.apache.pulsar.broker.stats.MetricsGenerator) PackagesManagementImpl(org.apache.pulsar.packages.management.core.impl.PackagesManagementImpl) ManagedLedgerFactory(org.apache.bookkeeper.mledger.ManagedLedgerFactory) SystemTopicBasedTopicPoliciesService(org.apache.pulsar.broker.service.SystemTopicBasedTopicPoliciesService) SchemaRegistryService(org.apache.pulsar.broker.service.schema.SchemaRegistryService) AuthenticationService(org.apache.pulsar.broker.authentication.AuthenticationService) ProtocolHandlers(org.apache.pulsar.broker.protocol.ProtocolHandlers) MetadataStoreExtended(org.apache.pulsar.metadata.api.extended.MetadataStoreExtended) NamespaceService(org.apache.pulsar.broker.namespace.NamespaceService) PulsarAdmin(org.apache.pulsar.client.admin.PulsarAdmin) Constructor(java.lang.reflect.Constructor) Supplier(java.util.function.Supplier) ArrayList(java.util.ArrayList) PulsarAdminBuilder(org.apache.pulsar.client.admin.PulsarAdminBuilder) CoordinationServiceImpl(org.apache.pulsar.metadata.coordination.impl.CoordinationServiceImpl) Lists(com.google.common.collect.Lists) AccessLevel(lombok.AccessLevel) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) PrometheusRawMetricsProvider(org.apache.pulsar.broker.stats.prometheus.PrometheusRawMetricsProvider) PulsarClient(org.apache.pulsar.client.api.PulsarClient) NamespaceBundle(org.apache.pulsar.common.naming.NamespaceBundle) LedgerOffloaderFactory(org.apache.bookkeeper.mledger.LedgerOffloaderFactory) NullLedgerOffloader(org.apache.bookkeeper.mledger.impl.NullLedgerOffloader) ClusterResources(org.apache.pulsar.broker.resources.ClusterResources) PrometheusMetricsServlet(org.apache.pulsar.broker.stats.prometheus.PrometheusMetricsServlet) LoadReportUpdaterTask(org.apache.pulsar.broker.loadbalance.LoadReportUpdaterTask) TransactionPendingAckStoreProvider(org.apache.pulsar.broker.transaction.pendingack.TransactionPendingAckStoreProvider) IOException(java.io.IOException) TransactionBufferClientImpl(org.apache.pulsar.broker.transaction.buffer.impl.TransactionBufferClientImpl) LeaderElectionState(org.apache.pulsar.metadata.api.coordination.LeaderElectionState) ExecutionException(java.util.concurrent.ExecutionException) Compactor(org.apache.pulsar.compaction.Compactor) PackagesStorage(org.apache.pulsar.packages.management.core.PackagesStorage) ClientConfiguration(org.apache.bookkeeper.conf.ClientConfiguration) InternalConfigurationData(org.apache.pulsar.common.conf.InternalConfigurationData) WorkerService(org.apache.pulsar.functions.worker.WorkerService) AuthorizationService(org.apache.pulsar.broker.authorization.AuthorizationService) LoadManagerShared(org.apache.pulsar.broker.loadbalance.impl.LoadManagerShared) ResourceUsageTopicTransportManager(org.apache.pulsar.broker.resourcegroup.ResourceUsageTopicTransportManager) DefaultThreadFactory(io.netty.util.concurrent.DefaultThreadFactory) ScheduledFuture(java.util.concurrent.ScheduledFuture) PulsarResources(org.apache.pulsar.broker.resources.PulsarResources) ServletException(javax.servlet.ServletException) AdditionalServletWithClassLoader(org.apache.pulsar.broker.web.plugin.servlet.AdditionalServletWithClassLoader) LoggerFactory(org.slf4j.LoggerFactory) TimeoutException(java.util.concurrent.TimeoutException) PackagesStorageProvider(org.apache.pulsar.packages.management.core.PackagesStorageProvider) BrokerInterceptors(org.apache.pulsar.broker.intercept.BrokerInterceptors) Notification(org.apache.pulsar.metadata.api.Notification) ResourceUsageTransportManager(org.apache.pulsar.broker.resourcegroup.ResourceUsageTransportManager) PulsarVersion(org.apache.pulsar.PulsarVersion) NamespaceName(org.apache.pulsar.common.naming.NamespaceName) Method(java.lang.reflect.Method) PulsarClientException(org.apache.pulsar.client.api.PulsarClientException) AdvertisedListener(org.apache.pulsar.policies.data.loadbalancer.AdvertisedListener) WebSocketService(org.apache.pulsar.websocket.WebSocketService) EventLoopUtil(org.apache.pulsar.common.util.netty.EventLoopUtil) ChannelInitializer(io.netty.channel.ChannelInitializer) OrderedScheduler(org.apache.bookkeeper.common.util.OrderedScheduler) ImmutableMap(com.google.common.collect.ImmutableMap) LoadResourceQuotaUpdaterTask(org.apache.pulsar.broker.loadbalance.LoadResourceQuotaUpdaterTask) Collection(java.util.Collection) OffloadPoliciesImpl(org.apache.pulsar.common.policies.data.OffloadPoliciesImpl) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) AuthenticationFactory(org.apache.pulsar.client.api.AuthenticationFactory) CompletionException(java.util.concurrent.CompletionException) MetadataStoreConfig(org.apache.pulsar.metadata.api.MetadataStoreConfig) InetSocketAddress(java.net.InetSocketAddress) SystemTopicBaseTxnBufferSnapshotService(org.apache.pulsar.broker.service.SystemTopicBaseTxnBufferSnapshotService) MultipleListenerValidator(org.apache.pulsar.broker.validator.MultipleListenerValidator) Objects(java.util.Objects) WebSocketReaderServlet(org.apache.pulsar.websocket.WebSocketReaderServlet) List(java.util.List) FutureUtil(org.apache.pulsar.common.util.FutureUtil) MLPendingAckStore(org.apache.pulsar.broker.transaction.pendingack.impl.MLPendingAckStore) ClientConfigurationData(org.apache.pulsar.client.impl.conf.ClientConfigurationData) HashedWheelTimer(io.netty.util.HashedWheelTimer) Timer(io.netty.util.Timer) Optional(java.util.Optional) PackagesManagement(org.apache.pulsar.packages.management.core.PackagesManagement) Setter(lombok.Setter) TopicName(org.apache.pulsar.common.naming.TopicName) DISABLE_RESOURCE_USAGE_TRANSPORT_MANAGER(org.apache.pulsar.broker.resourcegroup.ResourceUsageTransportManager.DISABLE_RESOURCE_USAGE_TRANSPORT_MANAGER) TRANSACTION_COORDINATOR_LOG(org.apache.pulsar.common.naming.TopicName.TRANSACTION_COORDINATOR_LOG) Getter(lombok.Getter) TransactionBufferClient(org.apache.pulsar.client.api.transaction.TransactionBufferClient) CompletableFuture(java.util.concurrent.CompletableFuture) DeploymentException(javax.websocket.DeploymentException) AtomicReference(java.util.concurrent.atomic.AtomicReference) ErrorNotifier(org.apache.pulsar.functions.worker.ErrorNotifier) Offloaders(org.apache.bookkeeper.mledger.offload.Offloaders) TransactionBufferProvider(org.apache.pulsar.broker.transaction.buffer.TransactionBufferProvider) WebService(org.apache.pulsar.broker.web.WebService) LinkedList(java.util.LinkedList) LeaderElectionService(org.apache.pulsar.broker.loadbalance.LeaderElectionService) EventLoopGroup(io.netty.channel.EventLoopGroup) Logger(org.slf4j.Logger) ReentrantLock(java.util.concurrent.locks.ReentrantLock) MalformedURLException(java.net.MalformedURLException) Preconditions.checkNotNull(com.google.common.base.Preconditions.checkNotNull) Maps(com.google.common.collect.Maps) OrderedExecutor(org.apache.bookkeeper.common.util.OrderedExecutor) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) TransactionBufferSnapshotService(org.apache.pulsar.broker.service.TransactionBufferSnapshotService) Condition(java.util.concurrent.locks.Condition) WebSocketProducerServlet(org.apache.pulsar.websocket.WebSocketProducerServlet) StringUtils.isBlank(org.apache.commons.lang3.StringUtils.isBlank) TwoPhaseCompactor(org.apache.pulsar.compaction.TwoPhaseCompactor) NotificationType(org.apache.pulsar.metadata.api.NotificationType) WebSocketPingPongServlet(org.apache.pulsar.websocket.WebSocketPingPongServlet) VisibleForTesting(com.google.common.annotations.VisibleForTesting) Collections(java.util.Collections) CoordinationService(org.apache.pulsar.metadata.api.coordination.CoordinationService) MetadataStoreFactory(org.apache.pulsar.metadata.api.MetadataStoreFactory) LoadSheddingTask(org.apache.pulsar.broker.loadbalance.LoadSheddingTask) LeaderElectionService(org.apache.pulsar.broker.loadbalance.LeaderElectionService) LoadResourceQuotaUpdaterTask(org.apache.pulsar.broker.loadbalance.LoadResourceQuotaUpdaterTask)

Example 2 with CoordinationService

use of org.apache.pulsar.metadata.api.coordination.CoordinationService in project pulsar by apache.

the class LeaderElectionTest method leaderNodeIsDeletedExternally.

@Test(dataProvider = "impl")
public void leaderNodeIsDeletedExternally(String provider, Supplier<String> urlSupplier) throws Exception {
    @Cleanup MetadataStoreExtended store = MetadataStoreExtended.create(urlSupplier.get(), MetadataStoreConfig.builder().build());
    @Cleanup CoordinationService coordinationService = new CoordinationServiceImpl(store);
    BlockingQueue<LeaderElectionState> notifications = new LinkedBlockingDeque<>();
    @Cleanup LeaderElection<String> leaderElection = coordinationService.getLeaderElection(String.class, "/my/leader-election", t -> {
        notifications.add(t);
    });
    LeaderElectionState les = leaderElection.elect("test-1").join();
    assertEquals(les, LeaderElectionState.Leading);
    assertEquals(notifications.poll(3, TimeUnit.SECONDS), LeaderElectionState.Leading);
    store.delete("/my/leader-election", Optional.empty()).join();
    assertEquals(notifications.poll(3, TimeUnit.SECONDS), LeaderElectionState.Leading);
    assertEquals(les, LeaderElectionState.Leading);
}
Also used : CoordinationService(org.apache.pulsar.metadata.api.coordination.CoordinationService) LinkedBlockingDeque(java.util.concurrent.LinkedBlockingDeque) CoordinationServiceImpl(org.apache.pulsar.metadata.coordination.impl.CoordinationServiceImpl) Cleanup(lombok.Cleanup) MetadataStoreExtended(org.apache.pulsar.metadata.api.extended.MetadataStoreExtended) LeaderElectionState(org.apache.pulsar.metadata.api.coordination.LeaderElectionState) Test(org.testng.annotations.Test)

Example 3 with CoordinationService

use of org.apache.pulsar.metadata.api.coordination.CoordinationService in project pulsar by apache.

the class LeaderElectionTest method revalidateLeaderWithDifferentSessionsSameValue.

@Test(dataProvider = "impl")
public void revalidateLeaderWithDifferentSessionsSameValue(String provider, Supplier<String> urlSupplier) throws Exception {
    if (provider.equals("Memory") || provider.equals("RocksDB")) {
        // There are no multiple sessions for the local memory provider
        return;
    }
    @Cleanup MetadataStoreExtended store = MetadataStoreExtended.create(urlSupplier.get(), MetadataStoreConfig.builder().build());
    @Cleanup MetadataStoreExtended store2 = MetadataStoreExtended.create(urlSupplier.get(), MetadataStoreConfig.builder().build());
    String path = newKey();
    @Cleanup CoordinationService cs = new CoordinationServiceImpl(store);
    @Cleanup LeaderElection<String> le = cs.getLeaderElection(String.class, path, __ -> {
    });
    store2.put(path, ObjectMapperFactory.getThreadLocal().writeValueAsBytes("test-1"), Optional.of(-1L), EnumSet.of(CreateOption.Ephemeral)).join();
    LeaderElectionState les = le.elect("test-1").join();
    assertEquals(les, LeaderElectionState.Leading);
    assertEquals(le.getLeaderValue().join(), Optional.of("test-1"));
    assertEquals(le.getLeaderValueIfPresent(), Optional.of("test-1"));
}
Also used : CoordinationService(org.apache.pulsar.metadata.api.coordination.CoordinationService) CoordinationServiceImpl(org.apache.pulsar.metadata.coordination.impl.CoordinationServiceImpl) Cleanup(lombok.Cleanup) MetadataStoreExtended(org.apache.pulsar.metadata.api.extended.MetadataStoreExtended) LeaderElectionState(org.apache.pulsar.metadata.api.coordination.LeaderElectionState) Test(org.testng.annotations.Test)

Example 4 with CoordinationService

use of org.apache.pulsar.metadata.api.coordination.CoordinationService in project pulsar by apache.

the class LeaderElectionTest method basicTest.

@Test(dataProvider = "impl")
public void basicTest(String provider, Supplier<String> urlSupplier) throws Exception {
    @Cleanup MetadataStoreExtended store = MetadataStoreExtended.create(urlSupplier.get(), MetadataStoreConfig.builder().build());
    @Cleanup CoordinationService coordinationService = new CoordinationServiceImpl(store);
    MetadataCache<String> cache = store.getMetadataCache(String.class);
    BlockingQueue<LeaderElectionState> notifications = new LinkedBlockingDeque<>();
    @Cleanup LeaderElection<String> leaderElection = coordinationService.getLeaderElection(String.class, "/my/leader-election", t -> {
        notifications.add(t);
    });
    assertEquals(cache.get("/my/leader-election").join(), Optional.empty());
    LeaderElectionState les = leaderElection.elect("test-1").join();
    assertEquals(les, LeaderElectionState.Leading);
    assertEquals(notifications.poll(3, TimeUnit.SECONDS), LeaderElectionState.Leading);
    assertEquals(cache.get("/my/leader-election").join(), Optional.of("test-1"));
    leaderElection.close();
    assertEquals(cache.get("/my/leader-election").join(), Optional.empty());
}
Also used : CoordinationService(org.apache.pulsar.metadata.api.coordination.CoordinationService) LinkedBlockingDeque(java.util.concurrent.LinkedBlockingDeque) CoordinationServiceImpl(org.apache.pulsar.metadata.coordination.impl.CoordinationServiceImpl) Cleanup(lombok.Cleanup) MetadataStoreExtended(org.apache.pulsar.metadata.api.extended.MetadataStoreExtended) LeaderElectionState(org.apache.pulsar.metadata.api.coordination.LeaderElectionState) Test(org.testng.annotations.Test)

Example 5 with CoordinationService

use of org.apache.pulsar.metadata.api.coordination.CoordinationService in project pulsar by apache.

the class LeaderElectionTest method closeAll.

@Test(dataProvider = "impl")
public void closeAll(String provider, Supplier<String> urlSupplier) throws Exception {
    @Cleanup MetadataStoreExtended store = MetadataStoreExtended.create(urlSupplier.get(), MetadataStoreConfig.builder().build());
    MetadataCache<String> cache = store.getMetadataCache(String.class);
    CoordinationService cs = new CoordinationServiceImpl(store);
    LeaderElection<String> le1 = cs.getLeaderElection(String.class, "/my/leader-election-1", t -> {
    });
    LeaderElection<String> le2 = cs.getLeaderElection(String.class, "/my/leader-election-2", t -> {
    });
    LeaderElectionState les1 = le1.elect("test-1").join();
    assertEquals(les1, LeaderElectionState.Leading);
    LeaderElectionState les2 = le2.elect("test-2").join();
    assertEquals(les2, LeaderElectionState.Leading);
    cs.close();
    assertEquals(cache.get("/my/leader-election-1").join(), Optional.empty());
    assertEquals(cache.get("/my/leader-election-2").join(), Optional.empty());
}
Also used : CoordinationService(org.apache.pulsar.metadata.api.coordination.CoordinationService) CoordinationServiceImpl(org.apache.pulsar.metadata.coordination.impl.CoordinationServiceImpl) Cleanup(lombok.Cleanup) MetadataStoreExtended(org.apache.pulsar.metadata.api.extended.MetadataStoreExtended) LeaderElectionState(org.apache.pulsar.metadata.api.coordination.LeaderElectionState) Test(org.testng.annotations.Test)

Aggregations

CoordinationService (org.apache.pulsar.metadata.api.coordination.CoordinationService)60 MetadataStoreExtended (org.apache.pulsar.metadata.api.extended.MetadataStoreExtended)60 CoordinationServiceImpl (org.apache.pulsar.metadata.coordination.impl.CoordinationServiceImpl)60 Cleanup (lombok.Cleanup)54 Test (org.testng.annotations.Test)54 LeaderElectionState (org.apache.pulsar.metadata.api.coordination.LeaderElectionState)30 SessionEvent (org.apache.pulsar.metadata.api.extended.SessionEvent)12 CompletionException (java.util.concurrent.CompletionException)9 VisibleForTesting (com.google.common.annotations.VisibleForTesting)6 Preconditions.checkNotNull (com.google.common.base.Preconditions.checkNotNull)6 ImmutableMap (com.google.common.collect.ImmutableMap)6 Lists (com.google.common.collect.Lists)6 Maps (com.google.common.collect.Maps)6 ChannelInitializer (io.netty.channel.ChannelInitializer)6 EventLoopGroup (io.netty.channel.EventLoopGroup)6 SocketChannel (io.netty.channel.socket.SocketChannel)6 HashedWheelTimer (io.netty.util.HashedWheelTimer)6 Timer (io.netty.util.Timer)6 DefaultThreadFactory (io.netty.util.concurrent.DefaultThreadFactory)6 IOException (java.io.IOException)6