Search in sources :

Example 11 with OpenLedgerCallback

use of org.apache.bookkeeper.mledger.AsyncCallbacks.OpenLedgerCallback in project incubator-pulsar by apache.

the class BrokerService method createPersistentTopic.

private void createPersistentTopic(final String topic, CompletableFuture<Topic> topicFuture) {
    final long topicCreateTimeMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime());
    TopicName topicName = TopicName.get(topic);
    if (!pulsar.getNamespaceService().isServiceUnitActive(topicName)) {
        // namespace is being unloaded
        String msg = String.format("Namespace is being unloaded, cannot add topic %s", topic);
        log.warn(msg);
        pulsar.getExecutor().submit(() -> topics.remove(topic, topicFuture));
        topicFuture.completeExceptionally(new ServiceUnitNotReadyException(msg));
        return;
    }
    getManagedLedgerConfig(topicName).thenAccept(managedLedgerConfig -> {
        // Once we have the configuration, we can proceed with the async open operation
        managedLedgerFactory.asyncOpen(topicName.getPersistenceNamingEncoding(), managedLedgerConfig, new OpenLedgerCallback() {

            @Override
            public void openLedgerComplete(ManagedLedger ledger, Object ctx) {
                try {
                    PersistentTopic persistentTopic = new PersistentTopic(topic, ledger, BrokerService.this);
                    CompletableFuture<Void> replicationFuture = persistentTopic.checkReplication();
                    replicationFuture.thenCompose(v -> {
                        // Also check dedup status
                        return persistentTopic.checkDeduplicationStatus();
                    }).thenRun(() -> {
                        log.info("Created topic {} - dedup is {}", topic, persistentTopic.isDeduplicationEnabled() ? "enabled" : "disabled");
                        long topicLoadLatencyMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime()) - topicCreateTimeMs;
                        pulsarStats.recordTopicLoadTimeValue(topic, topicLoadLatencyMs);
                        addTopicToStatsMaps(topicName, persistentTopic);
                        topicFuture.complete(persistentTopic);
                    }).exceptionally((ex) -> {
                        log.warn("Replication or dedup check failed. Removing topic from topics list {}, {}", topic, ex);
                        persistentTopic.stopReplProducers().whenComplete((v, exception) -> {
                            topics.remove(topic, topicFuture);
                            topicFuture.completeExceptionally(ex);
                        });
                        return null;
                    });
                } catch (NamingException e) {
                    log.warn("Failed to create topic {}-{}", topic, e.getMessage());
                    pulsar.getExecutor().submit(() -> topics.remove(topic, topicFuture));
                    topicFuture.completeExceptionally(e);
                }
            }

            @Override
            public void openLedgerFailed(ManagedLedgerException exception, Object ctx) {
                log.warn("Failed to create topic {}", topic, exception);
                pulsar.getExecutor().submit(() -> topics.remove(topic, topicFuture));
                topicFuture.completeExceptionally(new PersistenceException(exception));
            }
        }, null);
    }).exceptionally((exception) -> {
        log.warn("[{}] Failed to get topic configuration: {}", topic, exception.getMessage(), exception);
        // remove topic from topics-map in different thread to avoid possible deadlock if
        // createPersistentTopic-thread only tries to handle this future-result
        pulsar.getExecutor().submit(() -> topics.remove(topic, topicFuture));
        topicFuture.completeExceptionally(exception);
        return null;
    });
}
Also used : 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) ManagedLedger(org.apache.bookkeeper.mledger.ManagedLedger) TopicName(org.apache.pulsar.common.naming.TopicName) ServiceUnitNotReadyException(org.apache.pulsar.broker.service.BrokerServiceException.ServiceUnitNotReadyException) ManagedLedgerException(org.apache.bookkeeper.mledger.ManagedLedgerException) PersistentTopic(org.apache.pulsar.broker.service.persistent.PersistentTopic) NonPersistentTopic(org.apache.pulsar.broker.service.nonpersistent.NonPersistentTopic) PersistenceException(org.apache.pulsar.broker.service.BrokerServiceException.PersistenceException) NamingException(org.apache.pulsar.broker.service.BrokerServiceException.NamingException) OpenLedgerCallback(org.apache.bookkeeper.mledger.AsyncCallbacks.OpenLedgerCallback)

Example 12 with OpenLedgerCallback

use of org.apache.bookkeeper.mledger.AsyncCallbacks.OpenLedgerCallback in project incubator-pulsar by apache.

the class ManagedLedgerWriter method main.

public static void main(String[] args) throws Exception {
    final Arguments arguments = new Arguments();
    JCommander jc = new JCommander(arguments);
    jc.setProgramName("pulsar-perf-producer");
    try {
        jc.parse(args);
    } catch (ParameterException e) {
        System.out.println(e.getMessage());
        jc.usage();
        System.exit(-1);
    }
    if (arguments.help) {
        jc.usage();
        System.exit(-1);
    }
    arguments.testTime = TimeUnit.SECONDS.toMillis(arguments.testTime);
    // Dump config variables
    ObjectMapper m = new ObjectMapper();
    ObjectWriter w = m.writerWithDefaultPrettyPrinter();
    log.info("Starting Pulsar managed-ledger perf writer with config: {}", w.writeValueAsString(arguments));
    byte[] payloadData = new byte[arguments.msgSize];
    ByteBuf payloadBuffer = PooledByteBufAllocator.DEFAULT.directBuffer(arguments.msgSize);
    payloadBuffer.writerIndex(arguments.msgSize);
    // Now processing command line arguments
    String managedLedgerPrefix = "test-" + DigestUtils.sha1Hex(UUID.randomUUID().toString()).substring(0, 5);
    ClientConfiguration bkConf = new ClientConfiguration();
    bkConf.setUseV2WireProtocol(true);
    bkConf.setLedgerManagerFactoryClass(HierarchicalLedgerManagerFactory.class);
    bkConf.setAddEntryTimeout(30);
    bkConf.setReadEntryTimeout(30);
    bkConf.setThrottleValue(0);
    bkConf.setNumChannelsPerBookie(arguments.maxConnections);
    bkConf.setZkServers(arguments.zookeeperServers);
    ManagedLedgerFactoryConfig mlFactoryConf = new ManagedLedgerFactoryConfig();
    mlFactoryConf.setMaxCacheSize(0);
    ManagedLedgerFactory factory = new ManagedLedgerFactoryImpl(bkConf, mlFactoryConf);
    ManagedLedgerConfig mlConf = new ManagedLedgerConfig();
    mlConf.setEnsembleSize(arguments.ensembleSize);
    mlConf.setWriteQuorumSize(arguments.writeQuorum);
    mlConf.setAckQuorumSize(arguments.ackQuorum);
    mlConf.setMinimumRolloverTime(10, TimeUnit.MINUTES);
    mlConf.setMetadataEnsembleSize(arguments.ensembleSize);
    mlConf.setMetadataWriteQuorumSize(arguments.writeQuorum);
    mlConf.setMetadataAckQuorumSize(arguments.ackQuorum);
    mlConf.setDigestType(arguments.digestType);
    mlConf.setMaxSizePerLedgerMb(2048);
    List<CompletableFuture<ManagedLedger>> futures = new ArrayList<>();
    for (int i = 0; i < arguments.numManagedLedgers; i++) {
        String name = String.format("%s-%03d", managedLedgerPrefix, i);
        CompletableFuture<ManagedLedger> future = new CompletableFuture<>();
        futures.add(future);
        factory.asyncOpen(name, mlConf, new OpenLedgerCallback() {

            @Override
            public void openLedgerComplete(ManagedLedger ledger, Object ctx) {
                future.complete(ledger);
            }

            @Override
            public void openLedgerFailed(ManagedLedgerException exception, Object ctx) {
                future.completeExceptionally(exception);
            }
        }, null);
    }
    List<ManagedLedger> managedLedgers = futures.stream().map(CompletableFuture::join).collect(Collectors.toList());
    log.info("Created {} managed ledgers", managedLedgers.size());
    Runtime.getRuntime().addShutdownHook(new Thread() {

        public void run() {
            printAggregatedStats();
        }
    });
    Collections.shuffle(managedLedgers);
    AtomicBoolean isDone = new AtomicBoolean();
    List<List<ManagedLedger>> managedLedgersPerThread = Lists.partition(managedLedgers, Math.max(1, managedLedgers.size() / arguments.numThreads));
    for (int i = 0; i < arguments.numThreads; i++) {
        List<ManagedLedger> managedLedgersForThisThread = managedLedgersPerThread.get(i);
        int nunManagedLedgersForThisThread = managedLedgersForThisThread.size();
        long numMessagesForThisThread = arguments.numMessages / arguments.numThreads;
        int maxOutstandingForThisThread = arguments.maxOutstanding;
        executor.submit(() -> {
            try {
                final double msgRate = arguments.msgRate / (double) arguments.numThreads;
                final RateLimiter rateLimiter = RateLimiter.create(msgRate);
                // Acquire 1 sec worth of messages to have a slower ramp-up
                rateLimiter.acquire((int) msgRate);
                final long startTime = System.currentTimeMillis();
                final Semaphore semaphore = new Semaphore(maxOutstandingForThisThread);
                final AddEntryCallback addEntryCallback = new AddEntryCallback() {

                    @Override
                    public void addComplete(Position position, Object ctx) {
                        long sendTime = (Long) (ctx);
                        messagesSent.increment();
                        bytesSent.add(payloadData.length);
                        long latencyMicros = NANOSECONDS.toMicros(System.nanoTime() - sendTime);
                        recorder.recordValue(latencyMicros);
                        cumulativeRecorder.recordValue(latencyMicros);
                        semaphore.release();
                    }

                    @Override
                    public void addFailed(ManagedLedgerException exception, Object ctx) {
                        log.warn("Write error on message", exception);
                        System.exit(-1);
                    }
                };
                // Send messages on all topics/producers
                long totalSent = 0;
                while (true) {
                    for (int j = 0; j < nunManagedLedgersForThisThread; j++) {
                        if (arguments.testTime > 0) {
                            if (System.currentTimeMillis() - startTime > arguments.testTime) {
                                log.info("------------------- DONE -----------------------");
                                printAggregatedStats();
                                isDone.set(true);
                                Thread.sleep(5000);
                                System.exit(0);
                            }
                        }
                        if (numMessagesForThisThread > 0) {
                            if (totalSent++ >= numMessagesForThisThread) {
                                log.info("------------------- DONE -----------------------");
                                printAggregatedStats();
                                isDone.set(true);
                                Thread.sleep(5000);
                                System.exit(0);
                            }
                        }
                        semaphore.acquire();
                        rateLimiter.acquire();
                        final long sendTime = System.nanoTime();
                        managedLedgersForThisThread.get(j).asyncAddEntry(payloadBuffer, addEntryCallback, sendTime);
                    }
                }
            } catch (Throwable t) {
                log.error("Got error", t);
            }
        });
    }
    // Print report stats
    long oldTime = System.nanoTime();
    Histogram reportHistogram = null;
    while (true) {
        try {
            Thread.sleep(10000);
        } catch (InterruptedException e) {
            break;
        }
        if (isDone.get()) {
            break;
        }
        long now = System.nanoTime();
        double elapsed = (now - oldTime) / 1e9;
        double rate = messagesSent.sumThenReset() / elapsed;
        double throughput = bytesSent.sumThenReset() / elapsed / 1024 / 1024 * 8;
        reportHistogram = recorder.getIntervalHistogram(reportHistogram);
        log.info("Throughput produced: {}  msg/s --- {} Mbit/s --- Latency: mean: {} ms - med: {} - 95pct: {} - 99pct: {} - 99.9pct: {} - 99.99pct: {} - Max: {}", throughputFormat.format(rate), throughputFormat.format(throughput), dec.format(reportHistogram.getMean() / 1000.0), dec.format(reportHistogram.getValueAtPercentile(50) / 1000.0), dec.format(reportHistogram.getValueAtPercentile(95) / 1000.0), dec.format(reportHistogram.getValueAtPercentile(99) / 1000.0), dec.format(reportHistogram.getValueAtPercentile(99.9) / 1000.0), dec.format(reportHistogram.getValueAtPercentile(99.99) / 1000.0), dec.format(reportHistogram.getMaxValue() / 1000.0));
        reportHistogram.reset();
        oldTime = now;
    }
    factory.shutdown();
}
Also used : Histogram(org.HdrHistogram.Histogram) ManagedLedgerFactoryConfig(org.apache.bookkeeper.mledger.ManagedLedgerFactoryConfig) ManagedLedger(org.apache.bookkeeper.mledger.ManagedLedger) ArrayList(java.util.ArrayList) Semaphore(java.util.concurrent.Semaphore) ByteBuf(io.netty.buffer.ByteBuf) CompletableFuture(java.util.concurrent.CompletableFuture) ManagedLedgerException(org.apache.bookkeeper.mledger.ManagedLedgerException) JCommander(com.beust.jcommander.JCommander) ManagedLedgerFactory(org.apache.bookkeeper.mledger.ManagedLedgerFactory) ParameterException(com.beust.jcommander.ParameterException) ArrayList(java.util.ArrayList) List(java.util.List) ManagedLedgerConfig(org.apache.bookkeeper.mledger.ManagedLedgerConfig) AddEntryCallback(org.apache.bookkeeper.mledger.AsyncCallbacks.AddEntryCallback) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) ManagedLedgerFactoryImpl(org.apache.bookkeeper.mledger.impl.ManagedLedgerFactoryImpl) Position(org.apache.bookkeeper.mledger.Position) ObjectWriter(com.fasterxml.jackson.databind.ObjectWriter) RateLimiter(com.google.common.util.concurrent.RateLimiter) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) OpenLedgerCallback(org.apache.bookkeeper.mledger.AsyncCallbacks.OpenLedgerCallback) ClientConfiguration(org.apache.bookkeeper.conf.ClientConfiguration)

Example 13 with OpenLedgerCallback

use of org.apache.bookkeeper.mledger.AsyncCallbacks.OpenLedgerCallback in project incubator-pulsar by apache.

the class ManagedLedgerFactoryImpl method open.

@Override
public ManagedLedger open(String name, ManagedLedgerConfig config) throws InterruptedException, ManagedLedgerException {
    class Result {

        ManagedLedger l = null;

        ManagedLedgerException e = null;
    }
    final Result r = new Result();
    final CountDownLatch latch = new CountDownLatch(1);
    asyncOpen(name, config, new OpenLedgerCallback() {

        @Override
        public void openLedgerComplete(ManagedLedger ledger, Object ctx) {
            r.l = ledger;
            latch.countDown();
        }

        @Override
        public void openLedgerFailed(ManagedLedgerException exception, Object ctx) {
            r.e = exception;
            latch.countDown();
        }
    }, null);
    latch.await();
    if (r.e != null) {
        throw r.e;
    }
    return r.l;
}
Also used : ManagedLedgerException(org.apache.bookkeeper.mledger.ManagedLedgerException) ManagedLedgerException.getManagedLedgerException(org.apache.bookkeeper.mledger.ManagedLedgerException.getManagedLedgerException) ManagedLedger(org.apache.bookkeeper.mledger.ManagedLedger) CountDownLatch(java.util.concurrent.CountDownLatch) OpenLedgerCallback(org.apache.bookkeeper.mledger.AsyncCallbacks.OpenLedgerCallback)

Example 14 with OpenLedgerCallback

use of org.apache.bookkeeper.mledger.AsyncCallbacks.OpenLedgerCallback in project incubator-pulsar by apache.

the class PersistentTopicTest method setupMLAsyncCallbackMocks.

void setupMLAsyncCallbackMocks() {
    ledgerMock = mock(ManagedLedger.class);
    cursorMock = mock(ManagedCursor.class);
    final CompletableFuture<Void> closeFuture = new CompletableFuture<>();
    doReturn(new ArrayList<Object>()).when(ledgerMock).getCursors();
    doReturn("mockCursor").when(cursorMock).getName();
    // doNothing().when(cursorMock).asyncClose(new CloseCallback() {
    doAnswer(new Answer<Object>() {

        @Override
        public Object answer(InvocationOnMock invocationOnMock) throws Throwable {
            // return closeFuture.get();
            return closeFuture.complete(null);
        }
    }).when(cursorMock).asyncClose(new CloseCallback() {

        @Override
        public void closeComplete(Object ctx) {
            log.info("[{}] Successfully closed cursor ledger", "mockCursor");
            closeFuture.complete(null);
        }

        @Override
        public void closeFailed(ManagedLedgerException exception, Object ctx) {
            // isFenced.set(false);
            log.error("Error closing cursor for subscription", exception);
            closeFuture.completeExceptionally(new BrokerServiceException.PersistenceException(exception));
        }
    }, null);
    // call openLedgerComplete with ledgerMock on ML factory asyncOpen
    doAnswer(new Answer<Object>() {

        @Override
        public Object answer(InvocationOnMock invocationOnMock) throws Throwable {
            ((OpenLedgerCallback) invocationOnMock.getArguments()[2]).openLedgerComplete(ledgerMock, null);
            return null;
        }
    }).when(mlFactoryMock).asyncOpen(matches(".*success.*"), any(ManagedLedgerConfig.class), any(OpenLedgerCallback.class), anyObject());
    // call openLedgerFailed on ML factory asyncOpen
    doAnswer(new Answer<Object>() {

        @Override
        public Object answer(InvocationOnMock invocationOnMock) throws Throwable {
            ((OpenLedgerCallback) invocationOnMock.getArguments()[2]).openLedgerFailed(new ManagedLedgerException("Managed ledger failure"), null);
            return null;
        }
    }).when(mlFactoryMock).asyncOpen(matches(".*fail.*"), any(ManagedLedgerConfig.class), any(OpenLedgerCallback.class), anyObject());
    // call addComplete on ledger asyncAddEntry
    doAnswer(new Answer<Object>() {

        @Override
        public Object answer(InvocationOnMock invocationOnMock) throws Throwable {
            ((AddEntryCallback) invocationOnMock.getArguments()[1]).addComplete(new PositionImpl(1, 1), invocationOnMock.getArguments()[2]);
            return null;
        }
    }).when(ledgerMock).asyncAddEntry(any(ByteBuf.class), any(AddEntryCallback.class), anyObject());
    // call openCursorComplete on cursor asyncOpen
    doAnswer(new Answer<Object>() {

        @Override
        public Object answer(InvocationOnMock invocationOnMock) throws Throwable {
            ((OpenCursorCallback) invocationOnMock.getArguments()[2]).openCursorComplete(cursorMock, null);
            return null;
        }
    }).when(ledgerMock).asyncOpenCursor(matches(".*success.*"), any(InitialPosition.class), any(OpenCursorCallback.class), anyObject());
    // call deleteLedgerComplete on ledger asyncDelete
    doAnswer(new Answer<Object>() {

        @Override
        public Object answer(InvocationOnMock invocationOnMock) throws Throwable {
            ((DeleteLedgerCallback) invocationOnMock.getArguments()[0]).deleteLedgerComplete(null);
            return null;
        }
    }).when(ledgerMock).asyncDelete(any(DeleteLedgerCallback.class), anyObject());
    doAnswer(new Answer<Object>() {

        @Override
        public Object answer(InvocationOnMock invocationOnMock) throws Throwable {
            ((DeleteCursorCallback) invocationOnMock.getArguments()[1]).deleteCursorComplete(null);
            return null;
        }
    }).when(ledgerMock).asyncDeleteCursor(matches(".*success.*"), any(DeleteCursorCallback.class), anyObject());
    doAnswer((invokactionOnMock) -> {
        ((MarkDeleteCallback) invokactionOnMock.getArguments()[2]).markDeleteComplete(invokactionOnMock.getArguments()[3]);
        return null;
    }).when(cursorMock).asyncMarkDelete(anyObject(), anyObject(), any(MarkDeleteCallback.class), anyObject());
}
Also used : ManagedLedger(org.apache.bookkeeper.mledger.ManagedLedger) CloseCallback(org.apache.bookkeeper.mledger.AsyncCallbacks.CloseCallback) PositionImpl(org.apache.bookkeeper.mledger.impl.PositionImpl) InitialPosition(org.apache.pulsar.common.api.proto.PulsarApi.CommandSubscribe.InitialPosition) ByteBuf(io.netty.buffer.ByteBuf) ManagedCursor(org.apache.bookkeeper.mledger.ManagedCursor) MarkDeleteCallback(org.apache.bookkeeper.mledger.AsyncCallbacks.MarkDeleteCallback) CompletableFuture(java.util.concurrent.CompletableFuture) ManagedLedgerException(org.apache.bookkeeper.mledger.ManagedLedgerException) OpenCursorCallback(org.apache.bookkeeper.mledger.AsyncCallbacks.OpenCursorCallback) DeleteLedgerCallback(org.apache.bookkeeper.mledger.AsyncCallbacks.DeleteLedgerCallback) InvocationOnMock(org.mockito.invocation.InvocationOnMock) Matchers.anyObject(org.mockito.Matchers.anyObject) DeleteCursorCallback(org.apache.bookkeeper.mledger.AsyncCallbacks.DeleteCursorCallback) ManagedLedgerConfig(org.apache.bookkeeper.mledger.ManagedLedgerConfig) OpenLedgerCallback(org.apache.bookkeeper.mledger.AsyncCallbacks.OpenLedgerCallback) AddEntryCallback(org.apache.bookkeeper.mledger.AsyncCallbacks.AddEntryCallback)

Example 15 with OpenLedgerCallback

use of org.apache.bookkeeper.mledger.AsyncCallbacks.OpenLedgerCallback in project incubator-pulsar by apache.

the class PersistentTopicTest method testCreateTopicMLFailure.

@Test
public void testCreateTopicMLFailure() throws Exception {
    final String jinxedTopicName = "persistent://prop/use/ns-abc/topic3";
    doAnswer(new Answer<Object>() {

        @Override
        public Object answer(InvocationOnMock invocationOnMock) throws Throwable {
            new Thread(() -> {
                ((OpenLedgerCallback) invocationOnMock.getArguments()[2]).openLedgerFailed(new ManagedLedgerException("Managed ledger failure"), null);
            }).start();
            return null;
        }
    }).when(mlFactoryMock).asyncOpen(anyString(), any(ManagedLedgerConfig.class), any(OpenLedgerCallback.class), anyObject());
    CompletableFuture<Topic> future = brokerService.getTopic(jinxedTopicName);
    // wait for completion
    try {
        future.get(1, TimeUnit.SECONDS);
        fail("should have failed");
    } catch (TimeoutException e) {
        fail("Should not time out");
    } catch (Exception e) {
    // OK
    }
}
Also used : Matchers.anyString(org.mockito.Matchers.anyString) TimeoutException(java.util.concurrent.TimeoutException) ManagedLedgerException(org.apache.bookkeeper.mledger.ManagedLedgerException) ExecutionException(java.util.concurrent.ExecutionException) ManagedLedgerException(org.apache.bookkeeper.mledger.ManagedLedgerException) InvocationOnMock(org.mockito.invocation.InvocationOnMock) Matchers.anyObject(org.mockito.Matchers.anyObject) ManagedLedgerConfig(org.apache.bookkeeper.mledger.ManagedLedgerConfig) PersistentTopic(org.apache.pulsar.broker.service.persistent.PersistentTopic) CompactedTopic(org.apache.pulsar.compaction.CompactedTopic) OpenLedgerCallback(org.apache.bookkeeper.mledger.AsyncCallbacks.OpenLedgerCallback) TimeoutException(java.util.concurrent.TimeoutException) Test(org.testng.annotations.Test)

Aggregations

OpenLedgerCallback (org.apache.bookkeeper.mledger.AsyncCallbacks.OpenLedgerCallback)31 ManagedLedgerConfig (org.apache.bookkeeper.mledger.ManagedLedgerConfig)25 ManagedLedgerException (org.apache.bookkeeper.mledger.ManagedLedgerException)23 Test (org.testng.annotations.Test)20 ByteBuf (io.netty.buffer.ByteBuf)19 Matchers.anyObject (org.mockito.Matchers.anyObject)18 CompletableFuture (java.util.concurrent.CompletableFuture)17 ManagedLedger (org.apache.bookkeeper.mledger.ManagedLedger)17 CountDownLatch (java.util.concurrent.CountDownLatch)14 InvocationOnMock (org.mockito.invocation.InvocationOnMock)9 AddEntryCallback (org.apache.bookkeeper.mledger.AsyncCallbacks.AddEntryCallback)8 ManagedCursor (org.apache.bookkeeper.mledger.ManagedCursor)8 OpenCursorCallback (org.apache.bookkeeper.mledger.AsyncCallbacks.OpenCursorCallback)7 ManagedLedgerFactory (org.apache.bookkeeper.mledger.ManagedLedgerFactory)7 ArrayList (java.util.ArrayList)6 List (java.util.List)6 Executors (java.util.concurrent.Executors)6 TimeUnit (java.util.concurrent.TimeUnit)6 CloseCallback (org.apache.bookkeeper.mledger.AsyncCallbacks.CloseCallback)6 DeleteCursorCallback (org.apache.bookkeeper.mledger.AsyncCallbacks.DeleteCursorCallback)6