Search in sources :

Example 16 with ManagedLedgerConfig

use of org.apache.bookkeeper.mledger.ManagedLedgerConfig in project pulsar by yahoo.

the class ManagedCursorTest method testRateLimitMarkDelete.

@Test(timeOut = 20000)
void testRateLimitMarkDelete() throws Exception {
    ManagedLedgerConfig config = new ManagedLedgerConfig();
    // Throttle to 1/s
    config.setThrottleMarkDelete(1);
    ManagedLedger ledger = factory.open("my_test_ledger", config);
    ManagedCursor c1 = ledger.openCursor("c1");
    Position p1 = ledger.addEntry("dummy-entry-1".getBytes(Encoding));
    Position p2 = ledger.addEntry("dummy-entry-2".getBytes(Encoding));
    Position p3 = ledger.addEntry("dummy-entry-3".getBytes(Encoding));
    assertEquals(c1.getNumberOfEntriesInBacklog(), 3);
    c1.markDelete(p1);
    c1.markDelete(p2);
    c1.markDelete(p3);
    assertEquals(c1.getNumberOfEntriesInBacklog(), 0);
    // Re-open to recover from storage
    ManagedLedgerFactory factory2 = new ManagedLedgerFactoryImpl(bkc, bkc.getZkHandle());
    ledger = factory2.open("my_test_ledger", new ManagedLedgerConfig());
    c1 = ledger.openCursor("c1");
    // Only the 1st mark-delete was persisted
    assertEquals(c1.getNumberOfEntriesInBacklog(), 2);
    factory2.shutdown();
}
Also used : Position(org.apache.bookkeeper.mledger.Position) ManagedLedger(org.apache.bookkeeper.mledger.ManagedLedger) ManagedLedgerFactory(org.apache.bookkeeper.mledger.ManagedLedgerFactory) ManagedLedgerConfig(org.apache.bookkeeper.mledger.ManagedLedgerConfig) ManagedCursor(org.apache.bookkeeper.mledger.ManagedCursor) Test(org.testng.annotations.Test)

Example 17 with ManagedLedgerConfig

use of org.apache.bookkeeper.mledger.ManagedLedgerConfig in project pulsar by yahoo.

the class PersistentTopicConcurrentTest method setup.

@BeforeMethod
public void setup(Method m) throws Exception {
    super.setUp(m);
    ServiceConfiguration svcConfig = spy(new ServiceConfiguration());
    PulsarService pulsar = spy(new PulsarService(svcConfig));
    doReturn(svcConfig).when(pulsar).getConfiguration();
    mlFactoryMock = mock(ManagedLedgerFactory.class);
    ManagedLedgerFactory factory = new ManagedLedgerFactoryImpl(bkc, bkc.getZkHandle());
    ManagedLedger ledger = factory.open("my_test_ledger", new ManagedLedgerConfig().setMaxEntriesPerLedger(2));
    final ManagedCursor cursor = ledger.openCursor("c1");
    cursorMock = cursor;
    ledgerMock = ledger;
    mlFactoryMock = factory;
    doReturn(mlFactoryMock).when(pulsar).getManagedLedgerFactory();
    ZooKeeper mockZk = mock(ZooKeeper.class);
    doReturn(mockZk).when(pulsar).getZkClient();
    brokerService = spy(new BrokerService(pulsar));
    doReturn(brokerService).when(pulsar).getBrokerService();
    serverCnx = spy(new ServerCnx(brokerService));
    doReturn(true).when(serverCnx).isActive();
    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));
    final List<Position> addedEntries = Lists.newArrayList();
    for (int i = 0; i < 100; i++) {
        Position pos = ledger.addEntry("entry".getBytes());
        addedEntries.add(pos);
    }
}
Also used : NamespaceBundle(com.yahoo.pulsar.common.naming.NamespaceBundle) Position(org.apache.bookkeeper.mledger.Position) ManagedLedger(org.apache.bookkeeper.mledger.ManagedLedger) ServerCnx(com.yahoo.pulsar.broker.service.ServerCnx) ManagedCursor(org.apache.bookkeeper.mledger.ManagedCursor) 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) DestinationName(com.yahoo.pulsar.common.naming.DestinationName) ManagedLedgerConfig(org.apache.bookkeeper.mledger.ManagedLedgerConfig) BrokerService(com.yahoo.pulsar.broker.service.BrokerService) ManagedLedgerFactoryImpl(org.apache.bookkeeper.mledger.impl.ManagedLedgerFactoryImpl) BeforeMethod(org.testng.annotations.BeforeMethod)

Example 18 with ManagedLedgerConfig

use of org.apache.bookkeeper.mledger.ManagedLedgerConfig in project pulsar by yahoo.

the class BrokerService method getManagedLedgerConfig.

public CompletableFuture<ManagedLedgerConfig> getManagedLedgerConfig(DestinationName 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 destination
        Policies policies;
        try {
            policies = pulsar.getConfigurationCache().policiesCache().get(AdminResource.path("policies", namespace.getProperty(), namespace.getCluster(), namespace.getLocalName())).orElse(null);
        } 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 != null ? policies.persistence : null;
        RetentionPolicies retentionPolicies = policies != null ? policies.retention_policies : null;
        if (persistencePolicies == null) {
            // Apply default values
            persistencePolicies = new PersistencePolicies(serviceConfig.getManagedLedgerDefaultEnsembleSize(), serviceConfig.getManagedLedgerDefaultWriteQuorum(), serviceConfig.getManagedLedgerDefaultAckQuorum(), serviceConfig.getManagedLedgerDefaultMarkDeleteRateLimit());
        }
        if (retentionPolicies == null) {
            retentionPolicies = new RetentionPolicies(serviceConfig.getDefaultRetentionTimeInMinutes(), serviceConfig.getDefaultRetentionSizeInMB());
        }
        ManagedLedgerConfig config = new ManagedLedgerConfig();
        config.setEnsembleSize(persistencePolicies.getBookkeeperEnsemble());
        config.setWriteQuorumSize(persistencePolicies.getBookkeeperWriteQuorum());
        config.setAckQuorumSize(persistencePolicies.getBookkeeperAckQuorum());
        config.setThrottleMarkDelete(persistencePolicies.getManagedLedgerMaxMarkDeleteRate());
        config.setDigestType(DigestType.CRC32);
        config.setMaxUnackedRangesToPersist(serviceConfig.getManagedLedgerMaxUnackedRangesToPersist());
        config.setMaxEntriesPerLedger(serviceConfig.getManagedLedgerMaxEntriesPerLedger());
        config.setMinimumRolloverTime(serviceConfig.getManagedLedgerMinLedgerRolloverTimeMinutes(), TimeUnit.MINUTES);
        config.setMaximumRolloverTime(serviceConfig.getManagedLedgerMaxLedgerRolloverTimeMinutes(), TimeUnit.MINUTES);
        config.setMaxSizePerLedgerMb(2048);
        config.setMetadataEnsembleSize(serviceConfig.getManagedLedgerDefaultEnsembleSize());
        config.setMetadataWriteQuorumSize(serviceConfig.getManagedLedgerDefaultWriteQuorum());
        config.setMetadataAckQuorumSize(serviceConfig.getManagedLedgerDefaultAckQuorum());
        config.setMetadataMaxEntriesPerLedger(serviceConfig.getManagedLedgerCursorMaxEntriesPerLedger());
        config.setLedgerRolloverTimeout(serviceConfig.getManagedLedgerCursorRolloverTimeInSeconds());
        config.setRetentionTime(retentionPolicies.getRetentionTimeInMinutes(), TimeUnit.MINUTES);
        config.setRetentionSizeInMB(retentionPolicies.getRetentionSizeInMB());
        future.complete(config);
    }, (exception) -> future.completeExceptionally(exception)));
    return future;
}
Also used : RetentionPolicies(com.yahoo.pulsar.common.policies.data.RetentionPolicies) DefaultThreadFactory(io.netty.util.concurrent.DefaultThreadFactory) LoggerFactory(org.slf4j.LoggerFactory) NamespaceBundleStats(com.yahoo.pulsar.common.policies.data.loadbalancer.NamespaceBundleStats) Stat(org.apache.zookeeper.data.Stat) Policies(com.yahoo.pulsar.common.policies.data.Policies) EpollMode(io.netty.channel.epoll.EpollMode) PersistencePolicies(com.yahoo.pulsar.common.policies.data.PersistencePolicies) Preconditions.checkArgument(com.google.common.base.Preconditions.checkArgument) PersistentOfflineTopicStats(com.yahoo.pulsar.common.policies.data.PersistentOfflineTopicStats) ClusterData(com.yahoo.pulsar.common.policies.data.ClusterData) ManagedLedger(org.apache.bookkeeper.mledger.ManagedLedger) ManagedLedgerConfig(org.apache.bookkeeper.mledger.ManagedLedgerConfig) Map(java.util.Map) ZooKeeperCacheListener(com.yahoo.pulsar.zookeeper.ZooKeeperCacheListener) PulsarService(com.yahoo.pulsar.broker.PulsarService) FieldParser(com.yahoo.pulsar.common.util.FieldParser) PulsarClientImpl(com.yahoo.pulsar.client.impl.PulsarClientImpl) FutureUtil(com.yahoo.pulsar.client.util.FutureUtil) URI(java.net.URI) PulsarClient(com.yahoo.pulsar.client.api.PulsarClient) SystemUtils(org.apache.commons.lang.SystemUtils) DestinationName(com.yahoo.pulsar.common.naming.DestinationName) DigestType(org.apache.bookkeeper.client.BookKeeper.DigestType) PersistenceException(com.yahoo.pulsar.broker.service.BrokerServiceException.PersistenceException) Set(java.util.Set) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) PooledByteBufAllocator(io.netty.buffer.PooledByteBufAllocator) InetSocketAddress(java.net.InetSocketAddress) Executors(java.util.concurrent.Executors) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) ObjectMapperFactory(com.yahoo.pulsar.common.util.ObjectMapperFactory) ManagedLedgerException(org.apache.bookkeeper.mledger.ManagedLedgerException) Metrics(com.yahoo.pulsar.broker.stats.Metrics) List(java.util.List) StringUtils.isNotBlank(org.apache.commons.lang3.StringUtils.isNotBlank) AdminResource(com.yahoo.pulsar.broker.admin.AdminResource) ClientConfiguration(com.yahoo.pulsar.client.api.ClientConfiguration) PersistentTopic(com.yahoo.pulsar.broker.service.persistent.PersistentTopic) Optional(java.util.Optional) PulsarClientException(com.yahoo.pulsar.client.api.PulsarClientException) ManagedLedgerFactory(org.apache.bookkeeper.mledger.ManagedLedgerFactory) ChannelOption(io.netty.channel.ChannelOption) HashMap(java.util.HashMap) CompletableFuture(java.util.concurrent.CompletableFuture) AtomicReference(java.util.concurrent.atomic.AtomicReference) SafeRun.safeRun(org.apache.bookkeeper.mledger.util.SafeRun.safeRun) PersistentTopicStats(com.yahoo.pulsar.common.policies.data.PersistentTopicStats) EpollChannelOption(io.netty.channel.epoll.EpollChannelOption) Lists(com.google.common.collect.Lists) FieldContext(com.yahoo.pulsar.common.configuration.FieldContext) ByteBuf(io.netty.buffer.ByteBuf) EpollServerSocketChannel(io.netty.channel.epoll.EpollServerSocketChannel) RetentionPolicies(com.yahoo.pulsar.common.policies.data.RetentionPolicies) ConcurrentOpenHashSet(com.yahoo.pulsar.common.util.collections.ConcurrentOpenHashSet) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) EpollEventLoopGroup(io.netty.channel.epoll.EpollEventLoopGroup) ConcurrentOpenHashMap(com.yahoo.pulsar.common.util.collections.ConcurrentOpenHashMap) AdaptiveRecvByteBufAllocator(io.netty.channel.AdaptiveRecvByteBufAllocator) NamespaceBundle(com.yahoo.pulsar.common.naming.NamespaceBundle) NamespaceBundleFactory(com.yahoo.pulsar.common.naming.NamespaceBundleFactory) PersistentReplicator(com.yahoo.pulsar.broker.service.persistent.PersistentReplicator) ClusterReplicationMetrics(com.yahoo.pulsar.broker.stats.ClusterReplicationMetrics) Logger(org.slf4j.Logger) ZooKeeperDataCache(com.yahoo.pulsar.zookeeper.ZooKeeperDataCache) EventLoopGroup(io.netty.channel.EventLoopGroup) KeeperException(org.apache.zookeeper.KeeperException) Semaphore(java.util.concurrent.Semaphore) Preconditions.checkNotNull(com.google.common.base.Preconditions.checkNotNull) ServerMetadataException(com.yahoo.pulsar.broker.service.BrokerServiceException.ServerMetadataException) IOException(java.io.IOException) NamespaceName(com.yahoo.pulsar.common.naming.NamespaceName) Field(java.lang.reflect.Field) ServiceUnitNotReadyException(com.yahoo.pulsar.broker.service.BrokerServiceException.ServiceUnitNotReadyException) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) OpenLedgerCallback(org.apache.bookkeeper.mledger.AsyncCallbacks.OpenLedgerCallback) ServiceConfiguration(com.yahoo.pulsar.broker.ServiceConfiguration) PulsarWebResource(com.yahoo.pulsar.broker.web.PulsarWebResource) Closeable(java.io.Closeable) CollectionUtils.isEmpty(org.apache.commons.collections.CollectionUtils.isEmpty) AuthorizationManager(com.yahoo.pulsar.broker.authorization.AuthorizationManager) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) AuthenticationService(com.yahoo.pulsar.broker.authentication.AuthenticationService) NamespaceName(com.yahoo.pulsar.common.naming.NamespaceName) CompletableFuture(java.util.concurrent.CompletableFuture) Policies(com.yahoo.pulsar.common.policies.data.Policies) PersistencePolicies(com.yahoo.pulsar.common.policies.data.PersistencePolicies) RetentionPolicies(com.yahoo.pulsar.common.policies.data.RetentionPolicies) PersistencePolicies(com.yahoo.pulsar.common.policies.data.PersistencePolicies) ServiceConfiguration(com.yahoo.pulsar.broker.ServiceConfiguration) ManagedLedgerConfig(org.apache.bookkeeper.mledger.ManagedLedgerConfig)

Example 19 with ManagedLedgerConfig

use of org.apache.bookkeeper.mledger.ManagedLedgerConfig in project pulsar by yahoo.

the class PersistentTopics method getBacklog.

@GET
@Path("{property}/{cluster}/{namespace}/{destination}/backlog")
@ApiOperation(value = "Get estimated backlog for offline topic.")
@ApiResponses(value = { @ApiResponse(code = 403, message = "Don't have admin permission"), @ApiResponse(code = 404, message = "Namespace does not exist") })
public PersistentOfflineTopicStats getBacklog(@PathParam("property") String property, @PathParam("cluster") String cluster, @PathParam("namespace") String namespace, @PathParam("destination") @Encoded String destination, @QueryParam("authoritative") @DefaultValue("false") boolean authoritative) {
    destination = decode(destination);
    validateAdminAccessOnProperty(property);
    // note that we do not want to load the topic and hence skip validateAdminOperationOnDestination()
    try {
        policiesCache().get(path("policies", property, cluster, namespace));
    } catch (KeeperException.NoNodeException e) {
        log.warn("[{}] Failed to get topic backlog {}/{}/{}: Namespace does not exist", clientAppId(), property, cluster, namespace);
        throw new RestException(Status.NOT_FOUND, "Namespace does not exist");
    } catch (Exception e) {
        log.error("[{}] Failed to get topic backlog {}/{}/{}", clientAppId(), property, cluster, namespace, e);
        throw new RestException(e);
    }
    DestinationName dn = DestinationName.get(domain(), property, cluster, namespace, destination);
    PersistentOfflineTopicStats offlineTopicStats = null;
    try {
        offlineTopicStats = pulsar().getBrokerService().getOfflineTopicStat(dn);
        if (offlineTopicStats != null) {
            // offline topic stat has a cost - so use cached value until TTL
            long elapsedMs = System.currentTimeMillis() - offlineTopicStats.statGeneratedAt.getTime();
            if (TimeUnit.MINUTES.convert(elapsedMs, TimeUnit.MILLISECONDS) < OFFLINE_TOPIC_STAT_TTL_MINS) {
                return offlineTopicStats;
            }
        }
        final ManagedLedgerConfig config = pulsar().getBrokerService().getManagedLedgerConfig(dn).get();
        ManagedLedgerOfflineBacklog offlineTopicBacklog = new ManagedLedgerOfflineBacklog(config.getDigestType(), config.getPassword(), pulsar().getAdvertisedAddress(), false);
        offlineTopicStats = offlineTopicBacklog.estimateUnloadedTopicBacklog((ManagedLedgerFactoryImpl) pulsar().getManagedLedgerFactory(), dn);
        pulsar().getBrokerService().cacheOfflineTopicStats(dn, offlineTopicStats);
    } catch (Exception exception) {
        throw new RestException(exception);
    }
    return offlineTopicStats;
}
Also used : ManagedLedgerOfflineBacklog(org.apache.bookkeeper.mledger.impl.ManagedLedgerOfflineBacklog) PersistentOfflineTopicStats(com.yahoo.pulsar.common.policies.data.PersistentOfflineTopicStats) RestException(com.yahoo.pulsar.broker.web.RestException) DestinationName(com.yahoo.pulsar.common.naming.DestinationName) ManagedLedgerConfig(org.apache.bookkeeper.mledger.ManagedLedgerConfig) KeeperException(org.apache.zookeeper.KeeperException) RestException(com.yahoo.pulsar.broker.web.RestException) TopicBusyException(com.yahoo.pulsar.broker.service.BrokerServiceException.TopicBusyException) WebApplicationException(javax.ws.rs.WebApplicationException) PulsarClientException(com.yahoo.pulsar.client.api.PulsarClientException) PreconditionFailedException(com.yahoo.pulsar.client.admin.PulsarAdminException.PreconditionFailedException) SubscriptionBusyException(com.yahoo.pulsar.broker.service.BrokerServiceException.SubscriptionBusyException) NotFoundException(com.yahoo.pulsar.client.admin.PulsarAdminException.NotFoundException) NotAllowedException(com.yahoo.pulsar.broker.service.BrokerServiceException.NotAllowedException) KeeperException(org.apache.zookeeper.KeeperException) IOException(java.io.IOException) ManagedLedgerFactoryImpl(org.apache.bookkeeper.mledger.impl.ManagedLedgerFactoryImpl) Path(javax.ws.rs.Path) GET(javax.ws.rs.GET) ApiOperation(io.swagger.annotations.ApiOperation) ApiResponses(io.swagger.annotations.ApiResponses)

Example 20 with ManagedLedgerConfig

use of org.apache.bookkeeper.mledger.ManagedLedgerConfig in project pulsar by yahoo.

the class ManagedLedgerBkTest method testConcurrentMarkDelete.

@Test
public void testConcurrentMarkDelete() throws Exception {
    ManagedLedgerFactory factory = new ManagedLedgerFactoryImpl(bkc, zkc);
    ManagedLedgerConfig mlConfig = new ManagedLedgerConfig();
    mlConfig.setEnsembleSize(1).setAckQuorumSize(1).setMetadataEnsembleSize(1).setMetadataAckQuorumSize(1);
    // set the data ledger size
    mlConfig.setMaxEntriesPerLedger(100);
    // set the metadata ledger size to 1 to kick off many ledger switching cases
    mlConfig.setMetadataMaxEntriesPerLedger(10);
    ManagedLedger ledger = factory.open("ml-markdelete-ledger", mlConfig);
    final List<Position> addedEntries = Lists.newArrayList();
    int numCursors = 10;
    final CyclicBarrier barrier = new CyclicBarrier(numCursors);
    List<ManagedCursor> cursors = Lists.newArrayList();
    for (int i = 0; i < numCursors; i++) {
        cursors.add(ledger.openCursor(String.format("c%d", i)));
    }
    for (int i = 0; i < 50; i++) {
        Position pos = ledger.addEntry("entry".getBytes());
        addedEntries.add(pos);
    }
    List<Future<?>> futures = Lists.newArrayList();
    for (ManagedCursor cursor : cursors) {
        futures.add(executor.submit(() -> {
            barrier.await();
            for (Position position : addedEntries) {
                cursor.markDelete(position);
            }
            return null;
        }));
    }
    for (Future<?> future : futures) {
        future.get();
    }
    // Since in this test we roll-over the cursor ledger every 10 entries acknowledged, the background roll back
    // might still be happening when the futures are completed.
    Thread.sleep(1000);
    factory.shutdown();
}
Also used : Position(org.apache.bookkeeper.mledger.Position) ManagedLedger(org.apache.bookkeeper.mledger.ManagedLedger) CyclicBarrier(java.util.concurrent.CyclicBarrier) ManagedCursor(org.apache.bookkeeper.mledger.ManagedCursor) ManagedLedgerFactory(org.apache.bookkeeper.mledger.ManagedLedgerFactory) Future(java.util.concurrent.Future) ManagedLedgerConfig(org.apache.bookkeeper.mledger.ManagedLedgerConfig) Test(org.testng.annotations.Test)

Aggregations

ManagedLedgerConfig (org.apache.bookkeeper.mledger.ManagedLedgerConfig)82 Test (org.testng.annotations.Test)77 ManagedLedger (org.apache.bookkeeper.mledger.ManagedLedger)69 ManagedCursor (org.apache.bookkeeper.mledger.ManagedCursor)63 Position (org.apache.bookkeeper.mledger.Position)35 ManagedLedgerException (org.apache.bookkeeper.mledger.ManagedLedgerException)32 Entry (org.apache.bookkeeper.mledger.Entry)27 ManagedLedgerFactory (org.apache.bookkeeper.mledger.ManagedLedgerFactory)24 CountDownLatch (java.util.concurrent.CountDownLatch)22 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)13 CyclicBarrier (java.util.concurrent.CyclicBarrier)10 ManagedLedgerFactoryConfig (org.apache.bookkeeper.mledger.ManagedLedgerFactoryConfig)8 AsyncCallbacks (org.apache.bookkeeper.mledger.AsyncCallbacks)7 AddEntryCallback (org.apache.bookkeeper.mledger.AsyncCallbacks.AddEntryCallback)7 List (java.util.List)6 TimeUnit (java.util.concurrent.TimeUnit)6 AtomicReference (java.util.concurrent.atomic.AtomicReference)6 BKException (org.apache.bookkeeper.client.BKException)6 Lists (com.google.common.collect.Lists)5 Executors (java.util.concurrent.Executors)5