Search in sources :

Example 21 with OpenLedgerCallback

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

the class ManagedLedgerTest method asyncAPI.

@Test(timeOut = 20000)
public void asyncAPI() throws Throwable {
    final CountDownLatch counter = new CountDownLatch(1);
    factory.asyncOpen("my_test_ledger", new ManagedLedgerConfig(), new OpenLedgerCallback() {

        @Override
        public void openLedgerComplete(ManagedLedger ledger, Object ctx) {
            ledger.asyncOpenCursor("test-cursor", new OpenCursorCallback() {

                @Override
                public void openCursorComplete(ManagedCursor cursor, Object ctx) {
                    ManagedLedger ledger = (ManagedLedger) ctx;
                    ledger.asyncAddEntry("test".getBytes(Encoding), new AddEntryCallback() {

                        @Override
                        public void addComplete(Position position, Object ctx) {
                            @SuppressWarnings("unchecked") Pair<ManagedLedger, ManagedCursor> pair = (Pair<ManagedLedger, ManagedCursor>) ctx;
                            ManagedLedger ledger = pair.first;
                            ManagedCursor cursor = pair.second;
                            assertEquals(ledger.getNumberOfEntries(), 1);
                            assertEquals(ledger.getTotalSize(), "test".getBytes(Encoding).length);
                            cursor.asyncReadEntries(2, new ReadEntriesCallback() {

                                @Override
                                public void readEntriesComplete(List<Entry> entries, Object ctx) {
                                    ManagedCursor cursor = (ManagedCursor) ctx;
                                    assertEquals(entries.size(), 1);
                                    Entry entry = entries.get(0);
                                    assertEquals(new String(entry.getDataAndRelease(), Encoding), "test");
                                    log.debug("Mark-Deleting to position {}", entry.getPosition());
                                    cursor.asyncMarkDelete(entry.getPosition(), new MarkDeleteCallback() {

                                        @Override
                                        public void markDeleteComplete(Object ctx) {
                                            log.debug("Mark delete complete");
                                            ManagedCursor cursor = (ManagedCursor) ctx;
                                            assertEquals(cursor.hasMoreEntries(), false);
                                            counter.countDown();
                                        }

                                        @Override
                                        public void markDeleteFailed(ManagedLedgerException exception, Object ctx) {
                                            fail(exception.getMessage());
                                        }
                                    }, cursor);
                                }

                                @Override
                                public void readEntriesFailed(ManagedLedgerException exception, Object ctx) {
                                    fail(exception.getMessage());
                                }
                            }, cursor);
                        }

                        @Override
                        public void addFailed(ManagedLedgerException exception, Object ctx) {
                            fail(exception.getMessage());
                        }
                    }, new Pair<ManagedLedger, ManagedCursor>(ledger, cursor));
                }

                @Override
                public void openCursorFailed(ManagedLedgerException exception, Object ctx) {
                    fail(exception.getMessage());
                }
            }, ledger);
        }

        @Override
        public void openLedgerFailed(ManagedLedgerException exception, Object ctx) {
            fail(exception.getMessage());
        }
    }, null);
    counter.await();
    log.info("Test completed");
}
Also used : ReadEntriesCallback(org.apache.bookkeeper.mledger.AsyncCallbacks.ReadEntriesCallback) Position(org.apache.bookkeeper.mledger.Position) ManagedLedger(org.apache.bookkeeper.mledger.ManagedLedger) CountDownLatch(java.util.concurrent.CountDownLatch) ManagedCursor(org.apache.bookkeeper.mledger.ManagedCursor) MarkDeleteCallback(org.apache.bookkeeper.mledger.AsyncCallbacks.MarkDeleteCallback) OpenCursorCallback(org.apache.bookkeeper.mledger.AsyncCallbacks.OpenCursorCallback) Entry(org.apache.bookkeeper.mledger.Entry) ManagedLedgerException(org.apache.bookkeeper.mledger.ManagedLedgerException) List(java.util.List) ArrayList(java.util.ArrayList) ManagedLedgerConfig(org.apache.bookkeeper.mledger.ManagedLedgerConfig) OpenLedgerCallback(org.apache.bookkeeper.mledger.AsyncCallbacks.OpenLedgerCallback) AddEntryCallback(org.apache.bookkeeper.mledger.AsyncCallbacks.AddEntryCallback) Pair(org.apache.bookkeeper.mledger.util.Pair) Test(org.testng.annotations.Test)

Example 22 with OpenLedgerCallback

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

the class ManagedLedgerTest method concurrentAsyncOpen.

@Test(timeOut = 20000, enabled = false)
void concurrentAsyncOpen() throws Exception {
    final CountDownLatch counter = new CountDownLatch(2);
    class Result {

        ManagedLedger instance1 = null;

        ManagedLedger instance2 = null;
    }
    final Result result = new Result();
    factory.asyncOpen("my-test-ledger", new OpenLedgerCallback() {

        @Override
        public void openLedgerComplete(ManagedLedger ledger, Object ctx) {
            result.instance1 = ledger;
            counter.countDown();
        }

        @Override
        public void openLedgerFailed(ManagedLedgerException exception, Object ctx) {
        }
    }, null);
    factory.asyncOpen("my-test-ledger", new OpenLedgerCallback() {

        @Override
        public void openLedgerComplete(ManagedLedger ledger, Object ctx) {
            result.instance2 = ledger;
            counter.countDown();
        }

        @Override
        public void openLedgerFailed(ManagedLedgerException exception, Object ctx) {
        }
    }, null);
    counter.await();
    assertEquals(result.instance1, result.instance2);
    assertNotNull(result.instance1);
}
Also used : ManagedLedgerException(org.apache.bookkeeper.mledger.ManagedLedgerException) ManagedLedger(org.apache.bookkeeper.mledger.ManagedLedger) CountDownLatch(java.util.concurrent.CountDownLatch) OpenLedgerCallback(org.apache.bookkeeper.mledger.AsyncCallbacks.OpenLedgerCallback) Test(org.testng.annotations.Test)

Example 23 with OpenLedgerCallback

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

the class ManagedLedgerTest method asyncOpenClosedLedger.

// (timeOut = 20000)
@Test
public void asyncOpenClosedLedger() throws Exception {
    ManagedLedgerImpl ledger = (ManagedLedgerImpl) factory.open("my-closed-ledger");
    ManagedCursor c1 = ledger.openCursor("c1");
    ledger.addEntry("dummy-entry-1".getBytes(Encoding));
    c1.close();
    assertEquals(ledger.getNumberOfEntries(), 1);
    ledger.setFenced();
    final CountDownLatch counter = new CountDownLatch(1);
    class Result {

        ManagedLedger instance1 = null;
    }
    final Result result = new Result();
    factory.asyncOpen("my-closed-ledger", new OpenLedgerCallback() {

        @Override
        public void openLedgerComplete(ManagedLedger ledger, Object ctx) {
            result.instance1 = ledger;
            counter.countDown();
        }

        @Override
        public void openLedgerFailed(ManagedLedgerException exception, Object ctx) {
        }
    }, null);
    counter.await();
    assertNotNull(result.instance1);
    ManagedCursor c2 = result.instance1.openCursor("c1");
    List<Entry> entries = c2.readEntries(1);
    assertEquals(entries.size(), 1);
    entries.forEach(e -> e.release());
}
Also used : ManagedLedgerException(org.apache.bookkeeper.mledger.ManagedLedgerException) Entry(org.apache.bookkeeper.mledger.Entry) ManagedLedger(org.apache.bookkeeper.mledger.ManagedLedger) CountDownLatch(java.util.concurrent.CountDownLatch) OpenLedgerCallback(org.apache.bookkeeper.mledger.AsyncCallbacks.OpenLedgerCallback) ManagedCursor(org.apache.bookkeeper.mledger.ManagedCursor) Test(org.testng.annotations.Test)

Example 24 with OpenLedgerCallback

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

the class BrokerService method createPersistentTopic.

private CompletableFuture<Topic> createPersistentTopic(final String topic) throws RuntimeException {
    checkTopicNsOwnership(topic);
    final long topicCreateTimeMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime());
    DestinationName destinationName = DestinationName.get(topic);
    if (!pulsar.getNamespaceService().isServiceUnitActive(destinationName)) {
        // namespace is being unloaded
        String msg = String.format("Namespace is being unloaded, cannot add topic %s", topic);
        log.warn(msg);
        throw new RuntimeException(new ServiceUnitNotReadyException(msg));
    }
    final CompletableFuture<Topic> topicFuture = new CompletableFuture<>();
    getManagedLedgerConfig(destinationName).thenAccept(config -> {
        managedLedgerFactory.asyncOpen(destinationName.getPersistenceNamingEncoding(), config, new OpenLedgerCallback() {

            @Override
            public void openLedgerComplete(ManagedLedger ledger, Object ctx) {
                PersistentTopic persistentTopic = new PersistentTopic(topic, ledger, BrokerService.this);
                CompletableFuture<Void> replicationFuture = persistentTopic.checkReplication();
                replicationFuture.thenRun(() -> {
                    log.info("Created topic {}", topic);
                    long topicLoadLatencyMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime()) - topicCreateTimeMs;
                    pulsarStats.recordTopicLoadTimeValue(topic, topicLoadLatencyMs);
                    addTopicToStatsMaps(destinationName, persistentTopic);
                    topicFuture.complete(persistentTopic);
                });
                replicationFuture.exceptionally((ex) -> {
                    log.warn("Replication check failed. Removing topic from topics list {}, {}", topic, ex);
                    persistentTopic.stopReplProducers().whenComplete((v, exception) -> {
                        topics.remove(topic, topicFuture);
                        topicFuture.completeExceptionally(ex);
                    });
                    return null;
                });
            }

            @Override
            public void openLedgerFailed(ManagedLedgerException exception, Object ctx) {
                log.warn("Failed to create topic {}", topic, exception);
                topics.remove(topic, topicFuture);
                topicFuture.completeExceptionally(new PersistenceException(exception));
            }
        }, null);
    }).exceptionally((exception) -> {
        log.warn("[{}] Failed to get topic configuration: {}", topic, exception.getMessage(), exception);
        topics.remove(topic, topicFuture);
        topicFuture.completeExceptionally(exception);
        return null;
    });
    return topicFuture;
}
Also used : 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) ManagedLedger(org.apache.bookkeeper.mledger.ManagedLedger) ServiceUnitNotReadyException(com.yahoo.pulsar.broker.service.BrokerServiceException.ServiceUnitNotReadyException) CompletableFuture(java.util.concurrent.CompletableFuture) ManagedLedgerException(org.apache.bookkeeper.mledger.ManagedLedgerException) PersistentTopic(com.yahoo.pulsar.broker.service.persistent.PersistentTopic) DestinationName(com.yahoo.pulsar.common.naming.DestinationName) PersistenceException(com.yahoo.pulsar.broker.service.BrokerServiceException.PersistenceException) PersistentTopic(com.yahoo.pulsar.broker.service.persistent.PersistentTopic) OpenLedgerCallback(org.apache.bookkeeper.mledger.AsyncCallbacks.OpenLedgerCallback)

Example 25 with OpenLedgerCallback

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

the class ServerCnxTest method testSubscribeTimeout.

@Test(timeOut = 30000)
public void testSubscribeTimeout() throws Exception {
    resetChannel();
    setChannelConnected();
    // Delay the topic creation in a deterministic way
    CompletableFuture<Runnable> openTopicTask = new CompletableFuture<>();
    doAnswer(invocationOnMock -> {
        openTopicTask.complete(() -> {
            ((OpenLedgerCallback) invocationOnMock.getArguments()[2]).openLedgerComplete(ledgerMock, null);
        });
        return null;
    }).when(mlFactoryMock).asyncOpen(matches(".*success.*"), any(ManagedLedgerConfig.class), any(OpenLedgerCallback.class), anyObject());
    // In a subscribe timeout from client side we expect to see this sequence of commands :
    // 1. Subscribe
    // 2. close consumer (when the timeout is triggered, which may be before the consumer was created on the broker)
    // 3. Subscribe (triggered by reconnection logic)
    // These operations need to be serialized, to allow the last subscribe operation to finally succeed
    // (There can be more subscribe/close pairs in the sequence, depending on the client timeout
    ByteBuf subscribe1 = //
    Commands.newSubscribe(//
    successTopicName, successSubName, 1, /* consumer id */
    1, /* request id */
    SubType.Exclusive, 0, "test");
    channel.writeInbound(subscribe1);
    ByteBuf closeConsumer = Commands.newCloseConsumer(1, /* consumer id */
    2);
    channel.writeInbound(closeConsumer);
    ByteBuf subscribe2 = //
    Commands.newSubscribe(//
    successTopicName, successSubName, 1, /* consumer id */
    3, /* request id */
    SubType.Exclusive, 0, "test");
    channel.writeInbound(subscribe2);
    ByteBuf subscribe3 = //
    Commands.newSubscribe(//
    successTopicName, successSubName, 1, /* consumer id */
    4, /* request id */
    SubType.Exclusive, 0, "test");
    channel.writeInbound(subscribe3);
    ByteBuf subscribe4 = //
    Commands.newSubscribe(//
    successTopicName, successSubName, 1, /* consumer id */
    5, /* request id */
    SubType.Exclusive, 0, "test");
    channel.writeInbound(subscribe4);
    openTopicTask.get().run();
    Object response;
    synchronized (this) {
        // Close succeeds
        response = getResponse();
        assertEquals(response.getClass(), CommandSuccess.class);
        assertEquals(((CommandSuccess) response).getRequestId(), 2);
        // All other subscribe should fail
        response = getResponse();
        assertEquals(response.getClass(), CommandError.class);
        assertEquals(((CommandError) response).getRequestId(), 3);
        response = getResponse();
        assertEquals(response.getClass(), CommandError.class);
        assertEquals(((CommandError) response).getRequestId(), 4);
        response = getResponse();
        assertEquals(response.getClass(), CommandError.class);
        assertEquals(((CommandError) response).getRequestId(), 5);
        // We should not receive response for 1st producer, since it was cancelled by the close
        assertTrue(channel.outboundMessages().isEmpty());
        assertTrue(channel.isActive());
    }
    channel.finish();
}
Also used : CompletableFuture(java.util.concurrent.CompletableFuture) Matchers.anyObject(org.mockito.Matchers.anyObject) ManagedLedgerConfig(org.apache.bookkeeper.mledger.ManagedLedgerConfig) ByteBuf(io.netty.buffer.ByteBuf) OpenLedgerCallback(org.apache.bookkeeper.mledger.AsyncCallbacks.OpenLedgerCallback) 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