Search in sources :

Example 41 with Policies

use of com.yahoo.pulsar.common.policies.data.Policies in project pulsar by yahoo.

the class PersistentDispatcherFailoverConsumerTest method setup.

@BeforeMethod
public void setup() throws Exception {
    ServiceConfiguration svcConfig = spy(new ServiceConfiguration());
    PulsarService pulsar = spy(new PulsarService(svcConfig));
    doReturn(svcConfig).when(pulsar).getConfiguration();
    mlFactoryMock = mock(ManagedLedgerFactory.class);
    doReturn(mlFactoryMock).when(pulsar).getManagedLedgerFactory();
    ZooKeeper mockZk = mock(ZooKeeper.class);
    doReturn(mockZk).when(pulsar).getZkClient();
    configCacheService = mock(ConfigurationCacheService.class);
    @SuppressWarnings("unchecked") ZooKeeperDataCache<Policies> zkDataCache = mock(ZooKeeperDataCache.class);
    doReturn(zkDataCache).when(configCacheService).policiesCache();
    doReturn(configCacheService).when(pulsar).getConfigurationCache();
    brokerService = spy(new BrokerService(pulsar));
    doReturn(brokerService).when(pulsar).getBrokerService();
    serverCnx = spy(new ServerCnx(brokerService));
    doReturn(true).when(serverCnx).isActive();
    doReturn(true).when(serverCnx).isWritable();
    doReturn(new InetSocketAddress("localhost", 1234)).when(serverCnx).clientAddress();
    NamespaceService nsSvc = mock(NamespaceService.class);
    doReturn(nsSvc).when(pulsar).getNamespaceService();
    doReturn(true).when(nsSvc).isServiceUnitOwned(any(NamespaceBundle.class));
    doReturn(true).when(nsSvc).isServiceUnitActive(any(DestinationName.class));
    setupMLAsyncCallbackMocks();
}
Also used : NamespaceBundle(com.yahoo.pulsar.common.naming.NamespaceBundle) Policies(com.yahoo.pulsar.common.policies.data.Policies) InetSocketAddress(java.net.InetSocketAddress) ServerCnx(com.yahoo.pulsar.broker.service.ServerCnx) ZooKeeper(org.apache.zookeeper.ZooKeeper) ServiceConfiguration(com.yahoo.pulsar.broker.ServiceConfiguration) PulsarService(com.yahoo.pulsar.broker.PulsarService) NamespaceService(com.yahoo.pulsar.broker.namespace.NamespaceService) ManagedLedgerFactory(org.apache.bookkeeper.mledger.ManagedLedgerFactory) ConfigurationCacheService(com.yahoo.pulsar.broker.cache.ConfigurationCacheService) DestinationName(com.yahoo.pulsar.common.naming.DestinationName) BrokerService(com.yahoo.pulsar.broker.service.BrokerService) BeforeMethod(org.testng.annotations.BeforeMethod)

Example 42 with Policies

use of com.yahoo.pulsar.common.policies.data.Policies in project pulsar by yahoo.

the class LoadBalancerTest method createNamespace.

private void createNamespace(PulsarService pulsar, String namespace, int numBundles) throws Exception {
    Policies policies = new Policies();
    policies.bundles = getBundles(numBundles);
    ObjectMapper jsonMapper = ObjectMapperFactory.create();
    ZooKeeper globalZk = pulsar.getGlobalZkCache().getZooKeeper();
    String zpath = AdminResource.path("policies", namespace);
    ZkUtils.createFullPathOptimistic(globalZk, zpath, jsonMapper.writeValueAsBytes(policies), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
}
Also used : Policies(com.yahoo.pulsar.common.policies.data.Policies) NamespaceIsolationPolicies(com.yahoo.pulsar.common.policies.impl.NamespaceIsolationPolicies) ZooKeeper(org.apache.zookeeper.ZooKeeper) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper)

Example 43 with Policies

use of com.yahoo.pulsar.common.policies.data.Policies in project pulsar by yahoo.

the class NamespaceServiceTest method testSplitAndOwnBundles.

@Test
public void testSplitAndOwnBundles() throws Exception {
    OwnershipCache MockOwnershipCache = spy(pulsar.getNamespaceService().getOwnershipCache());
    doNothing().when(MockOwnershipCache).disableOwnership(any(NamespaceBundle.class));
    Field ownership = NamespaceService.class.getDeclaredField("ownershipCache");
    ownership.setAccessible(true);
    ownership.set(pulsar.getNamespaceService(), MockOwnershipCache);
    NamespaceService namespaceService = pulsar.getNamespaceService();
    NamespaceName nsname = new NamespaceName("pulsar/global/ns1");
    DestinationName dn = DestinationName.get("persistent://pulsar/global/ns1/topic-1");
    NamespaceBundles bundles = namespaceService.getNamespaceBundleFactory().getBundles(nsname);
    NamespaceBundle originalBundle = bundles.findBundle(dn);
    // Split bundle and take ownership of split bundles
    CompletableFuture<Void> result = namespaceService.splitAndOwnBundle(originalBundle);
    try {
        result.get();
    } catch (Exception e) {
        // make sure: no failure
        fail("split bundle faild", e);
    }
    NamespaceBundleFactory bundleFactory = this.pulsar.getNamespaceService().getNamespaceBundleFactory();
    NamespaceBundles updatedNsBundles = bundleFactory.getBundles(nsname);
    // new updated bundles shouldn't be null
    assertNotNull(updatedNsBundles);
    List<NamespaceBundle> bundleList = updatedNsBundles.getBundles();
    assertNotNull(bundles);
    NamespaceBundleFactory utilityFactory = NamespaceBundleFactory.createFactory(Hashing.crc32());
    // (1) validate bundleFactory-cache has newly split bundles and removed old parent bundle
    Pair<NamespaceBundles, List<NamespaceBundle>> splitBundles = splitBundles(utilityFactory, nsname, bundles, originalBundle);
    assertNotNull(splitBundles);
    Set<NamespaceBundle> splitBundleSet = new HashSet<>(splitBundles.getRight());
    splitBundleSet.removeAll(bundleList);
    assertTrue(splitBundleSet.isEmpty());
    // (2) validate LocalZookeeper policies updated with newly created split
    // bundles
    String path = joinPath(LOCAL_POLICIES_ROOT, nsname.toString());
    byte[] content = this.pulsar.getLocalZkCache().getZooKeeper().getData(path, null, new Stat());
    Policies policies = ObjectMapperFactory.getThreadLocal().readValue(content, Policies.class);
    NamespaceBundles localZkBundles = bundleFactory.getBundles(nsname, policies.bundles);
    assertTrue(updatedNsBundles.equals(localZkBundles));
    log.info("Policies: {}", policies);
    // (3) validate ownership of new split bundles by local owner
    bundleList.stream().forEach(b -> {
        try {
            byte[] data = this.pulsar.getLocalZkCache().getZooKeeper().getData(ServiceUnitZkUtils.path(b), null, new Stat());
            NamespaceEphemeralData node = ObjectMapperFactory.getThreadLocal().readValue(data, NamespaceEphemeralData.class);
            Assert.assertEquals(node.getNativeUrl(), this.pulsar.getBrokerServiceUrl());
        } catch (Exception e) {
            fail("failed to setup ownership", e);
        }
    });
}
Also used : NamespaceBundle(com.yahoo.pulsar.common.naming.NamespaceBundle) Policies(com.yahoo.pulsar.common.policies.data.Policies) NamespaceBundles(com.yahoo.pulsar.common.naming.NamespaceBundles) Field(java.lang.reflect.Field) NamespaceName(com.yahoo.pulsar.common.naming.NamespaceName) Stat(org.apache.zookeeper.data.Stat) DestinationName(com.yahoo.pulsar.common.naming.DestinationName) NamespaceBundleFactory(com.yahoo.pulsar.common.naming.NamespaceBundleFactory) List(java.util.List) HashSet(java.util.HashSet) Test(org.testng.annotations.Test)

Example 44 with Policies

use of com.yahoo.pulsar.common.policies.data.Policies in project pulsar by yahoo.

the class PersistentTopic method startReplProducers.

public void startReplProducers() {
    // read repl-cluster from policies to avoid restart of replicator which are in process of disconnect and close
    try {
        Policies policies = brokerService.pulsar().getConfigurationCache().policiesCache().get(AdminResource.path("policies", DestinationName.get(topic).getNamespace())).orElseThrow(() -> new KeeperException.NoNodeException());
        if (policies.replication_clusters != null) {
            Set<String> configuredClusters = Sets.newTreeSet(policies.replication_clusters);
            replicators.forEach((region, replicator) -> {
                if (configuredClusters.contains(region)) {
                    replicator.startProducer();
                }
            });
        }
    } catch (Exception e) {
        if (log.isDebugEnabled()) {
            log.debug("[{}] Error getting policies while starting repl-producers {}", topic, e.getMessage());
        }
        replicators.forEach((region, replicator) -> replicator.startProducer());
    }
}
Also used : ReplicationMetrics(com.yahoo.pulsar.broker.stats.ReplicationMetrics) SubType(com.yahoo.pulsar.common.api.proto.PulsarApi.CommandSubscribe.SubType) PersistentSubscriptionStats(com.yahoo.pulsar.common.policies.data.PersistentSubscriptionStats) LedgerInfo(com.yahoo.pulsar.common.policies.data.PersistentTopicInternalStats.LedgerInfo) NamingException(com.yahoo.pulsar.broker.service.BrokerServiceException.NamingException) ConsumerStats(com.yahoo.pulsar.common.policies.data.ConsumerStats) CloseCallback(org.apache.bookkeeper.mledger.AsyncCallbacks.CloseCallback) PersistentTopicInternalStats(com.yahoo.pulsar.common.policies.data.PersistentTopicInternalStats) LoggerFactory(org.slf4j.LoggerFactory) ObjectObjectHashMap(com.carrotsearch.hppc.ObjectObjectHashMap) NamespaceBundleStats(com.yahoo.pulsar.common.policies.data.loadbalancer.NamespaceBundleStats) Policies(com.yahoo.pulsar.common.policies.data.Policies) BacklogQuota(com.yahoo.pulsar.common.policies.data.BacklogQuota) Preconditions.checkArgument(com.google.common.base.Preconditions.checkArgument) OpenCursorCallback(org.apache.bookkeeper.mledger.AsyncCallbacks.OpenCursorCallback) ManagedCursor(org.apache.bookkeeper.mledger.ManagedCursor) TopicBusyException(com.yahoo.pulsar.broker.service.BrokerServiceException.TopicBusyException) ManagedLedger(org.apache.bookkeeper.mledger.ManagedLedger) ReplicatorStats(com.yahoo.pulsar.common.policies.data.ReplicatorStats) DeleteCursorCallback(org.apache.bookkeeper.mledger.AsyncCallbacks.DeleteCursorCallback) FutureUtil(com.yahoo.pulsar.client.util.FutureUtil) Objects(com.google.common.base.Objects) PositionImpl(org.apache.bookkeeper.mledger.impl.PositionImpl) DestinationName(com.yahoo.pulsar.common.naming.DestinationName) PersistenceException(com.yahoo.pulsar.broker.service.BrokerServiceException.PersistenceException) CursorStats(com.yahoo.pulsar.common.policies.data.PersistentTopicInternalStats.CursorStats) Set(java.util.Set) Position(org.apache.bookkeeper.mledger.Position) Instant(java.time.Instant) IndividualDeletedEntries(org.apache.bookkeeper.mledger.ManagedCursor.IndividualDeletedEntries) TopicFencedException(com.yahoo.pulsar.broker.service.BrokerServiceException.TopicFencedException) Lists(com.beust.jcommander.internal.Lists) ZoneId(java.time.ZoneId) Sets(com.google.common.collect.Sets) AddEntryCallback(org.apache.bookkeeper.mledger.AsyncCallbacks.AddEntryCallback) BrokerService(com.yahoo.pulsar.broker.service.BrokerService) ManagedLedgerException(org.apache.bookkeeper.mledger.ManagedLedgerException) Topic(com.yahoo.pulsar.broker.service.Topic) ManagedCursorImpl(org.apache.bookkeeper.mledger.impl.ManagedCursorImpl) Consumer(com.yahoo.pulsar.broker.service.Consumer) List(java.util.List) ManagedLedgerFencedException(org.apache.bookkeeper.mledger.ManagedLedgerException.ManagedLedgerFencedException) AdminResource(com.yahoo.pulsar.broker.admin.AdminResource) AsyncCallbacks(org.apache.bookkeeper.mledger.AsyncCallbacks) StatsOutputStream(com.yahoo.pulsar.utils.StatsOutputStream) Entry(org.apache.bookkeeper.mledger.Entry) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) CompletableFuture(java.util.concurrent.CompletableFuture) UnsupportedVersionException(com.yahoo.pulsar.broker.service.BrokerServiceException.UnsupportedVersionException) ReentrantReadWriteLock(java.util.concurrent.locks.ReentrantReadWriteLock) SubscriptionBusyException(com.yahoo.pulsar.broker.service.BrokerServiceException.SubscriptionBusyException) MessageImpl(com.yahoo.pulsar.client.impl.MessageImpl) PersistentTopicStats(com.yahoo.pulsar.common.policies.data.PersistentTopicStats) ServerCnx(com.yahoo.pulsar.broker.service.ServerCnx) ByteBuf(io.netty.buffer.ByteBuf) FastThreadLocal(io.netty.util.concurrent.FastThreadLocal) ConcurrentOpenHashSet(com.yahoo.pulsar.common.util.collections.ConcurrentOpenHashSet) ConsumerBusyException(com.yahoo.pulsar.broker.service.BrokerServiceException.ConsumerBusyException) ConcurrentOpenHashMap(com.yahoo.pulsar.common.util.collections.ConcurrentOpenHashMap) Codec(com.yahoo.pulsar.common.util.Codec) ManagedLedgerImpl(org.apache.bookkeeper.mledger.impl.ManagedLedgerImpl) ClusterReplicationMetrics(com.yahoo.pulsar.broker.stats.ClusterReplicationMetrics) Logger(org.slf4j.Logger) KeeperException(org.apache.zookeeper.KeeperException) BrokerServiceException(com.yahoo.pulsar.broker.service.BrokerServiceException) PublisherStats(com.yahoo.pulsar.common.policies.data.PublisherStats) Producer(com.yahoo.pulsar.broker.service.Producer) ServerMetadataException(com.yahoo.pulsar.broker.service.BrokerServiceException.ServerMetadataException) AtomicLongFieldUpdater(java.util.concurrent.atomic.AtomicLongFieldUpdater) NamespaceStats(com.yahoo.pulsar.broker.stats.NamespaceStats) Maps(com.google.common.collect.Maps) TimeUnit(java.util.concurrent.TimeUnit) DateTimeFormatter(java.time.format.DateTimeFormatter) Collections(java.util.Collections) Policies(com.yahoo.pulsar.common.policies.data.Policies) KeeperException(org.apache.zookeeper.KeeperException) NamingException(com.yahoo.pulsar.broker.service.BrokerServiceException.NamingException) TopicBusyException(com.yahoo.pulsar.broker.service.BrokerServiceException.TopicBusyException) PersistenceException(com.yahoo.pulsar.broker.service.BrokerServiceException.PersistenceException) TopicFencedException(com.yahoo.pulsar.broker.service.BrokerServiceException.TopicFencedException) ManagedLedgerException(org.apache.bookkeeper.mledger.ManagedLedgerException) ManagedLedgerFencedException(org.apache.bookkeeper.mledger.ManagedLedgerException.ManagedLedgerFencedException) UnsupportedVersionException(com.yahoo.pulsar.broker.service.BrokerServiceException.UnsupportedVersionException) SubscriptionBusyException(com.yahoo.pulsar.broker.service.BrokerServiceException.SubscriptionBusyException) ConsumerBusyException(com.yahoo.pulsar.broker.service.BrokerServiceException.ConsumerBusyException) KeeperException(org.apache.zookeeper.KeeperException) BrokerServiceException(com.yahoo.pulsar.broker.service.BrokerServiceException) ServerMetadataException(com.yahoo.pulsar.broker.service.BrokerServiceException.ServerMetadataException)

Example 45 with Policies

use of com.yahoo.pulsar.common.policies.data.Policies in project pulsar by yahoo.

the class PersistentTopic method checkReplication.

@Override
public CompletableFuture<Void> checkReplication() {
    DestinationName name = DestinationName.get(topic);
    if (!name.isGlobal()) {
        return CompletableFuture.completedFuture(null);
    }
    if (log.isDebugEnabled()) {
        log.debug("[{}] Checking replication status", name);
    }
    Policies policies = null;
    try {
        policies = brokerService.pulsar().getConfigurationCache().policiesCache().get(AdminResource.path("policies", name.getNamespace())).orElseThrow(() -> new KeeperException.NoNodeException());
    } catch (Exception e) {
        CompletableFuture<Void> future = new CompletableFuture<>();
        future.completeExceptionally(new ServerMetadataException(e));
        return future;
    }
    final int newMessageTTLinSeconds = policies.message_ttl_in_seconds;
    Set<String> configuredClusters;
    if (policies.replication_clusters != null) {
        configuredClusters = Sets.newTreeSet(policies.replication_clusters);
    } else {
        configuredClusters = Collections.emptySet();
    }
    String localCluster = brokerService.pulsar().getConfiguration().getClusterName();
    List<CompletableFuture<Void>> futures = Lists.newArrayList();
    // Check for missing replicators
    for (String cluster : configuredClusters) {
        if (cluster.equals(localCluster)) {
            continue;
        }
        if (!replicators.containsKey(cluster)) {
            futures.add(startReplicator(cluster));
        }
    }
    // Check for replicators to be stopped
    replicators.forEach((cluster, replicator) -> {
        // Update message TTL
        replicator.updateMessageTTL(newMessageTTLinSeconds);
        if (!cluster.equals(localCluster)) {
            if (!configuredClusters.contains(cluster)) {
                futures.add(removeReplicator(cluster));
            }
        }
    });
    return FutureUtil.waitForAll(futures);
}
Also used : CompletableFuture(java.util.concurrent.CompletableFuture) Policies(com.yahoo.pulsar.common.policies.data.Policies) ServerMetadataException(com.yahoo.pulsar.broker.service.BrokerServiceException.ServerMetadataException) DestinationName(com.yahoo.pulsar.common.naming.DestinationName) NamingException(com.yahoo.pulsar.broker.service.BrokerServiceException.NamingException) TopicBusyException(com.yahoo.pulsar.broker.service.BrokerServiceException.TopicBusyException) PersistenceException(com.yahoo.pulsar.broker.service.BrokerServiceException.PersistenceException) TopicFencedException(com.yahoo.pulsar.broker.service.BrokerServiceException.TopicFencedException) ManagedLedgerException(org.apache.bookkeeper.mledger.ManagedLedgerException) ManagedLedgerFencedException(org.apache.bookkeeper.mledger.ManagedLedgerException.ManagedLedgerFencedException) UnsupportedVersionException(com.yahoo.pulsar.broker.service.BrokerServiceException.UnsupportedVersionException) SubscriptionBusyException(com.yahoo.pulsar.broker.service.BrokerServiceException.SubscriptionBusyException) ConsumerBusyException(com.yahoo.pulsar.broker.service.BrokerServiceException.ConsumerBusyException) KeeperException(org.apache.zookeeper.KeeperException) BrokerServiceException(com.yahoo.pulsar.broker.service.BrokerServiceException) ServerMetadataException(com.yahoo.pulsar.broker.service.BrokerServiceException.ServerMetadataException)

Aggregations

Policies (com.yahoo.pulsar.common.policies.data.Policies)49 ApiOperation (io.swagger.annotations.ApiOperation)30 ApiResponses (io.swagger.annotations.ApiResponses)30 Path (javax.ws.rs.Path)30 RetentionPolicies (com.yahoo.pulsar.common.policies.data.RetentionPolicies)27 PersistencePolicies (com.yahoo.pulsar.common.policies.data.PersistencePolicies)26 KeeperException (org.apache.zookeeper.KeeperException)25 RestException (com.yahoo.pulsar.broker.web.RestException)24 SubscriptionBusyException (com.yahoo.pulsar.broker.service.BrokerServiceException.SubscriptionBusyException)19 NamespaceName (com.yahoo.pulsar.common.naming.NamespaceName)18 WebApplicationException (javax.ws.rs.WebApplicationException)17 PulsarServerException (com.yahoo.pulsar.broker.PulsarServerException)16 PulsarAdminException (com.yahoo.pulsar.client.admin.PulsarAdminException)15 NamespaceBundle (com.yahoo.pulsar.common.naming.NamespaceBundle)13 NoNodeException (org.apache.zookeeper.KeeperException.NoNodeException)13 Stat (org.apache.zookeeper.data.Stat)13 POST (javax.ws.rs.POST)11 GET (javax.ws.rs.GET)9 Test (org.testng.annotations.Test)9 DestinationName (com.yahoo.pulsar.common.naming.DestinationName)8