Search in sources :

Example 81 with NamespaceName

use of org.apache.pulsar.common.naming.NamespaceName in project incubator-pulsar by apache.

the class BrokerService method getManagedLedgerConfig.

public CompletableFuture<ManagedLedgerConfig> getManagedLedgerConfig(TopicName topicName) {
    CompletableFuture<ManagedLedgerConfig> future = new CompletableFuture<>();
    // Execute in background thread, since getting the policies might block if the z-node wasn't already cached
    pulsar.getOrderedExecutor().submitOrdered(topicName, safeRun(() -> {
        NamespaceName namespace = topicName.getNamespaceObject();
        ServiceConfiguration serviceConfig = pulsar.getConfiguration();
        // Get persistence policy for this topic
        Optional<Policies> policies = Optional.empty();
        try {
            policies = pulsar.getConfigurationCache().policiesCache().get(AdminResource.path(POLICIES, namespace.toString()));
        } catch (Throwable t) {
            // Ignoring since if we don't have policies, we fallback on the default
            log.warn("Got exception when reading persistence policy for {}: {}", topicName, t.getMessage(), t);
            future.completeExceptionally(t);
            return;
        }
        PersistencePolicies persistencePolicies = policies.map(p -> p.persistence).orElseGet(() -> new PersistencePolicies(serviceConfig.getManagedLedgerDefaultEnsembleSize(), serviceConfig.getManagedLedgerDefaultWriteQuorum(), serviceConfig.getManagedLedgerDefaultAckQuorum(), serviceConfig.getManagedLedgerDefaultMarkDeleteRateLimit()));
        RetentionPolicies retentionPolicies = policies.map(p -> p.retention_policies).orElseGet(() -> new RetentionPolicies(serviceConfig.getDefaultRetentionTimeInMinutes(), serviceConfig.getDefaultRetentionSizeInMB()));
        ManagedLedgerConfig managedLedgerConfig = new ManagedLedgerConfig();
        managedLedgerConfig.setEnsembleSize(persistencePolicies.getBookkeeperEnsemble());
        managedLedgerConfig.setWriteQuorumSize(persistencePolicies.getBookkeeperWriteQuorum());
        managedLedgerConfig.setAckQuorumSize(persistencePolicies.getBookkeeperAckQuorum());
        managedLedgerConfig.setThrottleMarkDelete(persistencePolicies.getManagedLedgerMaxMarkDeleteRate());
        managedLedgerConfig.setDigestType(serviceConfig.getManagedLedgerDigestType());
        managedLedgerConfig.setMaxUnackedRangesToPersist(serviceConfig.getManagedLedgerMaxUnackedRangesToPersist());
        managedLedgerConfig.setMaxUnackedRangesToPersistInZk(serviceConfig.getManagedLedgerMaxUnackedRangesToPersistInZooKeeper());
        managedLedgerConfig.setMaxEntriesPerLedger(serviceConfig.getManagedLedgerMaxEntriesPerLedger());
        managedLedgerConfig.setMinimumRolloverTime(serviceConfig.getManagedLedgerMinLedgerRolloverTimeMinutes(), TimeUnit.MINUTES);
        managedLedgerConfig.setMaximumRolloverTime(serviceConfig.getManagedLedgerMaxLedgerRolloverTimeMinutes(), TimeUnit.MINUTES);
        managedLedgerConfig.setMaxSizePerLedgerMb(2048);
        managedLedgerConfig.setMetadataEnsembleSize(serviceConfig.getManagedLedgerDefaultEnsembleSize());
        managedLedgerConfig.setMetadataWriteQuorumSize(serviceConfig.getManagedLedgerDefaultWriteQuorum());
        managedLedgerConfig.setMetadataAckQuorumSize(serviceConfig.getManagedLedgerDefaultAckQuorum());
        managedLedgerConfig.setMetadataMaxEntriesPerLedger(serviceConfig.getManagedLedgerCursorMaxEntriesPerLedger());
        managedLedgerConfig.setLedgerRolloverTimeout(serviceConfig.getManagedLedgerCursorRolloverTimeInSeconds());
        managedLedgerConfig.setRetentionTime(retentionPolicies.getRetentionTimeInMinutes(), TimeUnit.MINUTES);
        managedLedgerConfig.setRetentionSizeInMB(retentionPolicies.getRetentionSizeInMB());
        future.complete(managedLedgerConfig);
    }, (exception) -> future.completeExceptionally(exception)));
    return future;
}
Also used : RetentionPolicies(org.apache.pulsar.common.policies.data.RetentionPolicies) CreateMode(org.apache.zookeeper.CreateMode) ServiceUnitNotReadyException(org.apache.pulsar.broker.service.BrokerServiceException.ServiceUnitNotReadyException) NamingException(org.apache.pulsar.broker.service.BrokerServiceException.NamingException) PulsarClientImpl(org.apache.pulsar.client.impl.PulsarClientImpl) NotAllowedException(org.apache.pulsar.broker.service.BrokerServiceException.NotAllowedException) LoadManager(org.apache.pulsar.broker.loadbalance.LoadManager) FieldContext(org.apache.pulsar.common.configuration.FieldContext) Pair(org.apache.commons.lang3.tuple.Pair) Map(java.util.Map) ZooKeeperDataCache(org.apache.pulsar.zookeeper.ZooKeeperDataCache) PersistentOfflineTopicStats(org.apache.pulsar.common.policies.data.PersistentOfflineTopicStats) ReadWriteLock(java.util.concurrent.locks.ReadWriteLock) PersistencePolicies(org.apache.pulsar.common.policies.data.PersistencePolicies) Set(java.util.Set) ZooKeeperCacheListener(org.apache.pulsar.zookeeper.ZooKeeperCacheListener) PooledByteBufAllocator(io.netty.buffer.PooledByteBufAllocator) Executors(java.util.concurrent.Executors) ZkUtils(org.apache.bookkeeper.util.ZkUtils) NamespaceBundleFactory(org.apache.pulsar.common.naming.NamespaceBundleFactory) ConcurrentOpenHashSet(org.apache.pulsar.common.util.collections.ConcurrentOpenHashSet) StringUtils.isNotBlank(org.apache.commons.lang3.StringUtils.isNotBlank) ConcurrentOpenHashMap(org.apache.pulsar.common.util.collections.ConcurrentOpenHashMap) ClientBuilderImpl(org.apache.pulsar.client.impl.ClientBuilderImpl) ManagedLedgerFactory(org.apache.bookkeeper.mledger.ManagedLedgerFactory) ChannelOption(io.netty.channel.ChannelOption) AuthenticationService(org.apache.pulsar.broker.authentication.AuthenticationService) ReentrantReadWriteLock(java.util.concurrent.locks.ReentrantReadWriteLock) EventType(org.apache.pulsar.broker.zookeeper.aspectj.ClientCnxnAspect.EventType) ServerMetadataException(org.apache.pulsar.broker.service.BrokerServiceException.ServerMetadataException) Lists(com.google.common.collect.Lists) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) PulsarClient(org.apache.pulsar.client.api.PulsarClient) NamespaceBundle(org.apache.pulsar.common.naming.NamespaceBundle) PersistentDispatcherMultipleConsumers(org.apache.pulsar.broker.service.persistent.PersistentDispatcherMultipleConsumers) ClientCnxnAspect(org.apache.pulsar.broker.zookeeper.aspectj.ClientCnxnAspect) PulsarWebResource(org.apache.pulsar.broker.web.PulsarWebResource) SslContext(io.netty.handler.ssl.SslContext) IOException(java.io.IOException) Field(java.lang.reflect.Field) PulsarService(org.apache.pulsar.broker.PulsarService) OpenLedgerCallback(org.apache.bookkeeper.mledger.AsyncCallbacks.OpenLedgerCallback) POLICIES(org.apache.pulsar.broker.cache.ConfigurationCacheService.POLICIES) CollectionUtils.isEmpty(org.apache.commons.collections.CollectionUtils.isEmpty) AuthorizationService(org.apache.pulsar.broker.authorization.AuthorizationService) Metrics(org.apache.pulsar.common.stats.Metrics) DefaultThreadFactory(io.netty.util.concurrent.DefaultThreadFactory) PersistentTopicStats(org.apache.pulsar.common.policies.data.PersistentTopicStats) Ids(org.apache.zookeeper.ZooDefs.Ids) AdminResource(org.apache.pulsar.broker.admin.AdminResource) ObjectMapperFactory(org.apache.pulsar.common.util.ObjectMapperFactory) LoggerFactory(org.slf4j.LoggerFactory) ClusterData(org.apache.pulsar.common.policies.data.ClusterData) Stat(org.apache.zookeeper.data.Stat) Preconditions.checkArgument(com.google.common.base.Preconditions.checkArgument) ManagedLedger(org.apache.bookkeeper.mledger.ManagedLedger) ManagedLedgerConfig(org.apache.bookkeeper.mledger.ManagedLedgerConfig) NamespaceName(org.apache.pulsar.common.naming.NamespaceName) URI(java.net.URI) PulsarClientException(org.apache.pulsar.client.api.PulsarClientException) DigestType(org.apache.bookkeeper.client.BookKeeper.DigestType) EventLoopUtil(org.apache.pulsar.common.util.netty.EventLoopUtil) OrderedScheduler(org.apache.bookkeeper.common.util.OrderedScheduler) Predicate(java.util.function.Predicate) InetSocketAddress(java.net.InetSocketAddress) ManagedLedgerException(org.apache.bookkeeper.mledger.ManagedLedgerException) List(java.util.List) PersistentTopic(org.apache.pulsar.broker.service.persistent.PersistentTopic) FutureUtil(org.apache.pulsar.common.util.FutureUtil) Queues(com.google.common.collect.Queues) ClientConfigurationData(org.apache.pulsar.client.impl.conf.ClientConfigurationData) EventListner(org.apache.pulsar.broker.zookeeper.aspectj.ClientCnxnAspect.EventListner) ClientBuilder(org.apache.pulsar.client.api.ClientBuilder) Optional(java.util.Optional) NamespaceBundleStats(org.apache.pulsar.policies.data.loadbalancer.NamespaceBundleStats) ConcurrentLinkedQueue(java.util.concurrent.ConcurrentLinkedQueue) LongAdder(java.util.concurrent.atomic.LongAdder) TopicName(org.apache.pulsar.common.naming.TopicName) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) HashMap(java.util.HashMap) CompletableFuture(java.util.concurrent.CompletableFuture) AtomicReference(java.util.concurrent.atomic.AtomicReference) SafeRun.safeRun(org.apache.bookkeeper.mledger.util.SafeRun.safeRun) ByteBuf(io.netty.buffer.ByteBuf) AdaptiveRecvByteBufAllocator(io.netty.channel.AdaptiveRecvByteBufAllocator) TopicDomain(org.apache.pulsar.common.naming.TopicDomain) ClusterReplicationMetrics(org.apache.pulsar.broker.stats.ClusterReplicationMetrics) FieldParser(org.apache.pulsar.common.util.FieldParser) RetentionPolicies(org.apache.pulsar.common.policies.data.RetentionPolicies) Logger(org.slf4j.Logger) EventLoopGroup(io.netty.channel.EventLoopGroup) KeeperException(org.apache.zookeeper.KeeperException) Semaphore(java.util.concurrent.Semaphore) ServiceConfiguration(org.apache.pulsar.broker.ServiceConfiguration) Preconditions.checkNotNull(com.google.common.base.Preconditions.checkNotNull) PersistenceException(org.apache.pulsar.broker.service.BrokerServiceException.PersistenceException) Maps(com.google.common.collect.Maps) ImmutablePair(org.apache.commons.lang3.tuple.ImmutablePair) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) Policies(org.apache.pulsar.common.policies.data.Policies) Closeable(java.io.Closeable) NonPersistentTopic(org.apache.pulsar.broker.service.nonpersistent.NonPersistentTopic) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) Collections(java.util.Collections) NamespaceName(org.apache.pulsar.common.naming.NamespaceName) CompletableFuture(java.util.concurrent.CompletableFuture) PersistencePolicies(org.apache.pulsar.common.policies.data.PersistencePolicies) ServiceConfiguration(org.apache.pulsar.broker.ServiceConfiguration) Optional(java.util.Optional) ManagedLedgerConfig(org.apache.bookkeeper.mledger.ManagedLedgerConfig)

Example 82 with NamespaceName

use of org.apache.pulsar.common.naming.NamespaceName in project incubator-pulsar by apache.

the class BrokerService method onUpdate.

@Override
public void onUpdate(String path, Policies data, Stat stat) {
    final NamespaceName namespace = NamespaceName.get(NamespaceBundleFactory.getNamespaceFromPoliciesPath(path));
    log.info("{} updating with {}", path, data);
    topics.forEach((name, topicFuture) -> {
        if (namespace.includes(TopicName.get(name))) {
            // If the topic is already created, immediately apply the updated policies, otherwise once the topic is
            // created it'll apply the policies update
            topicFuture.thenAccept(topic -> {
                if (log.isDebugEnabled()) {
                    log.debug("Notifying topic that policies have changed: {}", name);
                }
                topic.onPoliciesUpdate(data);
            });
        }
    });
}
Also used : NamespaceName(org.apache.pulsar.common.naming.NamespaceName)

Example 83 with NamespaceName

use of org.apache.pulsar.common.naming.NamespaceName in project incubator-pulsar by apache.

the class NamespaceService method splitAndOwnBundleOnceAndRetry.

void splitAndOwnBundleOnceAndRetry(NamespaceBundle bundle, boolean unload, AtomicInteger counter, CompletableFuture<Void> unloadFuture) {
    CompletableFuture<NamespaceBundles> updateFuture = new CompletableFuture<>();
    final Pair<NamespaceBundles, List<NamespaceBundle>> splittedBundles = bundleFactory.splitBundles(bundle, 2);
    // Split and updateNamespaceBundles. Update may fail because of concurrent write to Zookeeper.
    if (splittedBundles != null) {
        checkNotNull(splittedBundles.getLeft());
        checkNotNull(splittedBundles.getRight());
        checkArgument(splittedBundles.getRight().size() == 2, "bundle has to be split in two bundles");
        NamespaceName nsname = bundle.getNamespaceObject();
        if (LOG.isDebugEnabled()) {
            LOG.debug("[{}] splitAndOwnBundleOnce: {}, counter: {},  2 bundles: {}, {}", nsname.toString(), bundle.getBundleRange(), counter.get(), splittedBundles != null ? splittedBundles.getRight().get(0).getBundleRange() : "null splittedBundles", splittedBundles != null ? splittedBundles.getRight().get(1).getBundleRange() : "null splittedBundles");
        }
        try {
            // take ownership of newly split bundles
            for (NamespaceBundle sBundle : splittedBundles.getRight()) {
                checkNotNull(ownershipCache.tryAcquiringOwnership(sBundle));
            }
            updateNamespaceBundles(nsname, splittedBundles.getLeft(), (rc, path, zkCtx, stat) -> {
                if (rc == Code.OK.intValue()) {
                    // invalidate cache as zookeeper has new split
                    // namespace bundle
                    bundleFactory.invalidateBundleCache(bundle.getNamespaceObject());
                    updateFuture.complete(splittedBundles.getLeft());
                } else if (rc == Code.BADVERSION.intValue()) {
                    KeeperException keeperException = KeeperException.create(KeeperException.Code.get(rc));
                    String msg = format("failed to update namespace policies [%s], NamespaceBundle: %s " + "due to %s, counter: %d", nsname.toString(), bundle.getBundleRange(), keeperException.getMessage(), counter.get());
                    LOG.warn(msg);
                    updateFuture.completeExceptionally(new ServerMetadataException(keeperException));
                } else {
                    String msg = format("failed to update namespace policies [%s], NamespaceBundle: %s due to %s", nsname.toString(), bundle.getBundleRange(), KeeperException.create(KeeperException.Code.get(rc)).getMessage());
                    LOG.warn(msg);
                    updateFuture.completeExceptionally(new ServiceUnitNotReadyException(msg));
                }
            });
        } catch (Exception e) {
            String msg = format("failed to acquire ownership of split bundle for namespace [%s], %s", nsname.toString(), e.getMessage());
            LOG.warn(msg, e);
            updateFuture.completeExceptionally(new ServiceUnitNotReadyException(msg));
        }
    } else {
        String msg = format("bundle %s not found under namespace", bundle.toString());
        LOG.warn(msg);
        updateFuture.completeExceptionally(new ServiceUnitNotReadyException(msg));
    }
    // If success updateNamespaceBundles, then do invalidateBundleCache and unload.
    // Else retry splitAndOwnBundleOnceAndRetry.
    updateFuture.whenCompleteAsync((r, t) -> {
        if (t != null) {
            // retry several times on BadVersion
            if ((t instanceof ServerMetadataException) && (counter.decrementAndGet() >= 0)) {
                pulsar.getOrderedExecutor().submit(() -> splitAndOwnBundleOnceAndRetry(bundle, unload, counter, unloadFuture));
            } else {
                // Retry enough, or meet other exception
                String msg2 = format(" %s not success update nsBundles, counter %d, reason %s", bundle.toString(), counter.get(), t.getMessage());
                LOG.warn(msg2);
                unloadFuture.completeExceptionally(new ServiceUnitNotReadyException(msg2));
            }
            return;
        }
        // success updateNamespaceBundles
        try {
            // disable old bundle in memory
            getOwnershipCache().updateBundleState(bundle, false);
            // update bundled_topic cache for load-report-generation
            pulsar.getBrokerService().refreshTopicToStatsMaps(bundle);
            loadManager.get().setLoadReportForceUpdateFlag();
            if (unload) {
                // unload new split bundles
                r.getBundles().forEach(splitBundle -> {
                    try {
                        unloadNamespaceBundle(splitBundle);
                    } catch (Exception e) {
                        LOG.warn("Failed to unload split bundle {}", splitBundle, e);
                        throw new RuntimeException("Failed to unload split bundle " + splitBundle, e);
                    }
                });
            }
            unloadFuture.complete(null);
        } catch (Exception e) {
            String msg1 = format("failed to disable bundle %s under namespace [%s] with error %s", bundle.getNamespaceObject().toString(), bundle.toString(), e.getMessage());
            LOG.warn(msg1, e);
            unloadFuture.completeExceptionally(new ServiceUnitNotReadyException(msg1));
        }
        return;
    }, pulsar.getOrderedExecutor());
}
Also used : NamespaceBundle(org.apache.pulsar.common.naming.NamespaceBundle) NamespaceBundles(org.apache.pulsar.common.naming.NamespaceBundles) ServiceUnitNotReadyException(org.apache.pulsar.broker.service.BrokerServiceException.ServiceUnitNotReadyException) ServerMetadataException(org.apache.pulsar.broker.service.BrokerServiceException.ServerMetadataException) KeeperException(org.apache.zookeeper.KeeperException) PulsarServerException(org.apache.pulsar.broker.PulsarServerException) NamespaceName(org.apache.pulsar.common.naming.NamespaceName) ServiceUnitNotReadyException(org.apache.pulsar.broker.service.BrokerServiceException.ServiceUnitNotReadyException) CompletableFuture(java.util.concurrent.CompletableFuture) ServerMetadataException(org.apache.pulsar.broker.service.BrokerServiceException.ServerMetadataException) List(java.util.List) KeeperException(org.apache.zookeeper.KeeperException)

Example 84 with NamespaceName

use of org.apache.pulsar.common.naming.NamespaceName in project incubator-pulsar by apache.

the class DispatchRateLimiter method registerLocalPoliciesListener.

/**
 * Register listener on namespace policy change to update dispatch-rate if required
 */
private void registerLocalPoliciesListener() {
    brokerService.pulsar().getConfigurationCache().policiesCache().registerListener((path, data, stat) -> {
        final NamespaceName namespace = TopicName.get(this.topicName).getNamespaceObject();
        final String cluster = brokerService.pulsar().getConfiguration().getClusterName();
        final String policiesPath = path(POLICIES, namespace.toString());
        if (policiesPath.equals(path)) {
            DispatchRate dispatchRate = data.clusterDispatchRate.get(cluster);
            // update dispatch-rate only if it's configured in policies else ignore
            if (dispatchRate != null) {
                final DispatchRate clusterDispatchRate = new DispatchRate(brokerService.pulsar().getConfiguration().getDispatchThrottlingRatePerTopicInMsg(), brokerService.pulsar().getConfiguration().getDispatchThrottlingRatePerTopicInByte(), 1);
                // cluster-throttling rate
                if (!isDispatchRateEnabled(dispatchRate) && isDispatchRateEnabled(clusterDispatchRate)) {
                    dispatchRate = clusterDispatchRate;
                }
                updateDispatchRate(dispatchRate);
            }
        }
    });
}
Also used : NamespaceName(org.apache.pulsar.common.naming.NamespaceName) DispatchRate(org.apache.pulsar.common.policies.data.DispatchRate)

Example 85 with NamespaceName

use of org.apache.pulsar.common.naming.NamespaceName in project incubator-pulsar by apache.

the class SimpleLoadManagerImpl method isBrokerAvailableForRebalancing.

// todo: changeme: this can be optimized, we don't have to iterate through everytime
private boolean isBrokerAvailableForRebalancing(String bundleName, long maxLoadLevel) {
    NamespaceName namespaceName = NamespaceName.get(LoadManagerShared.getNamespaceNameFromBundleName(bundleName));
    Map<Long, Set<ResourceUnit>> availableBrokers = sortedRankings.get();
    // this does not have "http://" in front, hacky but no time to pretty up
    Multimap<Long, ResourceUnit> brokers = getFinalCandidates(namespaceName, availableBrokers);
    for (Object broker : brokers.values()) {
        ResourceUnit underloadedRU = (ResourceUnit) broker;
        LoadReport currentLoadReport = currentLoadReports.get(underloadedRU);
        if (isBelowLoadLevel(currentLoadReport.getSystemResourceUsage(), maxLoadLevel)) {
            return true;
        }
    }
    return false;
}
Also used : ResourceUnit(org.apache.pulsar.broker.loadbalance.ResourceUnit) NamespaceName(org.apache.pulsar.common.naming.NamespaceName) Set(java.util.Set) HashSet(java.util.HashSet) LoadReport(org.apache.pulsar.policies.data.loadbalancer.LoadReport)

Aggregations

NamespaceName (org.apache.pulsar.common.naming.NamespaceName)99 WebTarget (javax.ws.rs.client.WebTarget)52 PulsarAdminException (org.apache.pulsar.client.admin.PulsarAdminException)52 Test (org.testng.annotations.Test)27 NamespaceBundle (org.apache.pulsar.common.naming.NamespaceBundle)26 List (java.util.List)15 MockedPulsarServiceBaseTest (org.apache.pulsar.broker.auth.MockedPulsarServiceBaseTest)13 RestException (org.apache.pulsar.broker.web.RestException)13 TopicName (org.apache.pulsar.common.naming.TopicName)13 Field (java.lang.reflect.Field)12 URL (java.net.URL)11 NamespaceBundles (org.apache.pulsar.common.naming.NamespaceBundles)11 Policies (org.apache.pulsar.common.policies.data.Policies)10 PulsarServerException (org.apache.pulsar.broker.PulsarServerException)8 BundlesData (org.apache.pulsar.common.policies.data.BundlesData)8 KeeperException (org.apache.zookeeper.KeeperException)8 ArrayList (java.util.ArrayList)7 Map (java.util.Map)7 HashSet (java.util.HashSet)6 CompletableFuture (java.util.concurrent.CompletableFuture)6