Search in sources :

Example 61 with GetResult

use of org.apache.pulsar.metadata.api.GetResult in project pulsar by apache.

the class NamespaceServiceTest method testUnloadNamespaceBundleFailure.

@Test
public void testUnloadNamespaceBundleFailure() throws Exception {
    final String topicName = "persistent://my-property/use/my-ns/my-topic1";
    pulsarClient.newConsumer().topic(topicName).subscriptionName("my-subscriber-name").subscribe();
    ConcurrentOpenHashMap<String, CompletableFuture<Optional<Topic>>> topics = pulsar.getBrokerService().getTopics();
    Topic spyTopic = spy(topics.get(topicName).get().get());
    topics.clear();
    CompletableFuture<Optional<Topic>> topicFuture = CompletableFuture.completedFuture(Optional.of(spyTopic));
    // add mock topic
    topics.put(topicName, topicFuture);
    doAnswer((Answer<CompletableFuture<Void>>) invocation -> {
        CompletableFuture<Void> result = new CompletableFuture<>();
        result.completeExceptionally(new RuntimeException("first time failed"));
        return result;
    }).when(spyTopic).close(false);
    NamespaceBundle bundle = pulsar.getNamespaceService().getBundle(TopicName.get(topicName));
    pulsar.getNamespaceService().unloadNamespaceBundle(bundle).join();
    Optional<GetResult> res = this.pulsar.getLocalMetadataStore().get(ServiceUnitUtils.path(bundle)).join();
    assertFalse(res.isPresent());
}
Also used : Topic(org.apache.pulsar.broker.service.Topic) ObjectMapperFactory(org.apache.pulsar.common.util.ObjectMapperFactory) LoggerFactory(org.slf4j.LoggerFactory) LoadManager(org.apache.pulsar.broker.loadbalance.LoadManager) Test(org.testng.annotations.Test) AfterMethod(org.testng.annotations.AfterMethod) NamespaceBundleSplitAlgorithm(org.apache.pulsar.common.naming.NamespaceBundleSplitAlgorithm) NamespaceBundles(org.apache.pulsar.common.naming.NamespaceBundles) Pair(org.apache.commons.lang3.tuple.Pair) ManagedLedger(org.apache.bookkeeper.mledger.ManagedLedger) Mockito.doAnswer(org.mockito.Mockito.doAnswer) Map(java.util.Map) NamespaceName(org.apache.pulsar.common.naming.NamespaceName) URI(java.net.URI) Mockito.doReturn(org.mockito.Mockito.doReturn) Assert.assertFalse(org.testng.Assert.assertFalse) Method(java.lang.reflect.Method) AdvertisedListener(org.apache.pulsar.policies.data.loadbalancer.AdvertisedListener) EnumSet(java.util.EnumSet) BeforeMethod(org.testng.annotations.BeforeMethod) Set(java.util.Set) LocalPolicies(org.apache.pulsar.common.policies.data.LocalPolicies) Assert.assertNotNull(org.testng.Assert.assertNotNull) LoadReport(org.apache.pulsar.policies.data.loadbalancer.LoadReport) BrokerTestBase(org.apache.pulsar.broker.service.BrokerTestBase) Consumer(org.apache.pulsar.client.api.Consumer) NamespaceBundleFactory(org.apache.pulsar.common.naming.NamespaceBundleFactory) List(java.util.List) PersistentTopic(org.apache.pulsar.broker.service.persistent.PersistentTopic) ConcurrentOpenHashMap(org.apache.pulsar.common.util.collections.ConcurrentOpenHashMap) ModularLoadManagerWrapper(org.apache.pulsar.broker.loadbalance.impl.ModularLoadManagerWrapper) Optional(java.util.Optional) NamespaceBundleStats(org.apache.pulsar.policies.data.loadbalancer.NamespaceBundleStats) Awaitility(org.awaitility.Awaitility) Mockito.mock(org.mockito.Mockito.mock) ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) TopicName(org.apache.pulsar.common.naming.TopicName) Assert.assertNull(org.testng.Assert.assertNull) Assert.assertEquals(org.testng.Assert.assertEquals) ModularLoadManagerImpl(org.apache.pulsar.broker.loadbalance.impl.ModularLoadManagerImpl) CompletableFuture(java.util.concurrent.CompletableFuture) Hashing(com.google.common.hash.Hashing) Mockito.spy(org.mockito.Mockito.spy) BundleData(org.apache.pulsar.broker.BundleData) HashSet(java.util.HashSet) Answer(org.mockito.stubbing.Answer) Lists(com.google.common.collect.Lists) GetResult(org.apache.pulsar.metadata.api.GetResult) Assert(org.testng.Assert) CollectionUtils(org.apache.commons.collections.CollectionUtils) BundlesData(org.apache.pulsar.common.policies.data.BundlesData) NamespaceBundle(org.apache.pulsar.common.naming.NamespaceBundle) Logger(org.slf4j.Logger) LocalBrokerData(org.apache.pulsar.policies.data.loadbalancer.LocalBrokerData) Assert.fail(org.testng.Assert.fail) CreateOption(org.apache.pulsar.metadata.api.extended.CreateOption) Mockito.when(org.mockito.Mockito.when) Field(java.lang.reflect.Field) Maps(com.google.common.collect.Maps) Assert.assertNotEquals(org.junit.Assert.assertNotEquals) TimeUnit(java.util.concurrent.TimeUnit) Policies(org.apache.pulsar.common.policies.data.Policies) AsyncLoadingCache(com.github.benmanes.caffeine.cache.AsyncLoadingCache) LookupResult(org.apache.pulsar.broker.lookup.LookupResult) Assert.assertTrue(org.testng.Assert.assertTrue) NamespaceBundle(org.apache.pulsar.common.naming.NamespaceBundle) CompletableFuture(java.util.concurrent.CompletableFuture) Optional(java.util.Optional) GetResult(org.apache.pulsar.metadata.api.GetResult) Topic(org.apache.pulsar.broker.service.Topic) PersistentTopic(org.apache.pulsar.broker.service.persistent.PersistentTopic) Test(org.testng.annotations.Test)

Example 62 with GetResult

use of org.apache.pulsar.metadata.api.GetResult in project kop by streamnative.

the class MessageFetchContext method handleEntries.

private void handleEntries(final List<Entry> entries, final TopicPartition topicPartition, final FetchRequest.PartitionData partitionData, final KafkaTopicConsumerManager tcm, final ManagedCursor cursor, final AtomicLong cursorOffset, final boolean readCommitted) {
    final long highWatermark = MessageMetadataUtils.getHighWatermark(cursor.getManagedLedger());
    // Add new offset back to TCM after entries are read successfully
    tcm.add(cursorOffset.get(), Pair.of(cursor, cursorOffset.get()));
    PartitionLog partitionLog = requestHandler.getReplicaManager().getPartitionLog(topicPartition, namespacePrefix);
    final long lso = (readCommitted ? partitionLog.firstUndecidedOffset().orElse(highWatermark) : highWatermark);
    List<Entry> committedEntries = entries;
    if (readCommitted) {
        committedEntries = getCommittedEntries(entries, lso);
        if (log.isDebugEnabled()) {
            log.debug("Request {}: read {} entries but only {} entries are committed", header, entries.size(), committedEntries.size());
        }
    } else {
        if (log.isDebugEnabled()) {
            log.debug("Request {}: read {} entries", header, entries.size());
        }
    }
    if (committedEntries.isEmpty()) {
        addErrorPartitionResponse(topicPartition, Errors.NONE);
        return;
    }
    // use compatible magic value by apiVersion
    short apiVersion = header.apiVersion();
    final byte magic;
    if (apiVersion <= 1) {
        magic = RecordBatch.MAGIC_VALUE_V0;
    } else if (apiVersion <= 3) {
        magic = RecordBatch.MAGIC_VALUE_V1;
    } else {
        magic = RecordBatch.CURRENT_MAGIC_VALUE;
    }
    CompletableFuture<String> groupNameFuture = requestHandler.getCurrentConnectedGroup().computeIfAbsent(clientHost, clientHost -> {
        CompletableFuture<String> future = new CompletableFuture<>();
        String groupIdPath = GroupIdUtils.groupIdPathFormat(clientHost, header.clientId());
        requestHandler.getMetadataStore().get(requestHandler.getGroupIdStoredPath() + groupIdPath).thenAccept(getResultOpt -> {
            if (getResultOpt.isPresent()) {
                GetResult getResult = getResultOpt.get();
                future.complete(new String(getResult.getValue() == null ? new byte[0] : getResult.getValue(), StandardCharsets.UTF_8));
            } else {
                future.complete("");
            }
        }).exceptionally(ex -> {
            future.completeExceptionally(ex);
            return null;
        });
        return future;
    });
    // this part is heavyweight, and we should not execute in the ManagedLedger Ordered executor thread
    groupNameFuture.whenCompleteAsync((groupName, ex) -> {
        if (ex != null) {
            log.error("Get groupId failed.", ex);
            groupName = "";
        }
        final long startDecodingEntriesNanos = MathUtils.nowInNano();
        final DecodeResult decodeResult = requestHandler.getEntryFormatter().decode(entries, magic);
        requestHandler.requestStats.getFetchDecodeStats().registerSuccessfulEvent(MathUtils.elapsedNanos(startDecodingEntriesNanos), TimeUnit.NANOSECONDS);
        decodeResults.add(decodeResult);
        final MemoryRecords kafkaRecords = decodeResult.getRecords();
        // collect consumer metrics
        decodeResult.updateConsumerStats(topicPartition, entries.size(), groupName, statsLogger);
        List<FetchResponse.AbortedTransaction> abortedTransactions;
        if (readCommitted) {
            abortedTransactions = partitionLog.getAbortedIndexList(partitionData.fetchOffset);
        } else {
            abortedTransactions = null;
        }
        responseData.put(topicPartition, new PartitionData<>(Errors.NONE, highWatermark, lso, // TODO: should it be changed to the logStartOffset?
        highWatermark, abortedTransactions, kafkaRecords));
        bytesReadable.getAndAdd(kafkaRecords.sizeInBytes());
        tryComplete();
    }, requestHandler.getDecodeExecutor());
}
Also used : MathUtils(org.apache.bookkeeper.common.util.MathUtils) IsolationLevel(org.apache.kafka.common.requests.IsolationLevel) NonDurableCursorImpl(org.apache.bookkeeper.mledger.impl.NonDurableCursorImpl) ResponseCallbackWrapper(org.apache.kafka.common.requests.ResponseCallbackWrapper) OpStatsLogger(org.apache.bookkeeper.stats.OpStatsLogger) ManagedCursor(org.apache.bookkeeper.mledger.ManagedCursor) Handle(io.netty.util.Recycler.Handle) Pair(org.apache.commons.lang3.tuple.Pair) RequestHeader(org.apache.kafka.common.requests.RequestHeader) Map(java.util.Map) RecordBatch(org.apache.kafka.common.record.RecordBatch) FetchResponse(org.apache.kafka.common.requests.FetchResponse) DelayedOperationPurgatory(io.streamnative.pulsar.handlers.kop.utils.delayed.DelayedOperationPurgatory) PositionImpl(org.apache.bookkeeper.mledger.impl.PositionImpl) TopicPartition(org.apache.kafka.common.TopicPartition) PartitionLog(io.streamnative.pulsar.handlers.kop.storage.PartitionLog) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) MessageMetadataUtils(io.streamnative.pulsar.handlers.kop.utils.MessageMetadataUtils) TransactionCoordinator(io.streamnative.pulsar.handlers.kop.coordinator.transaction.TransactionCoordinator) Collectors(java.util.stream.Collectors) StandardCharsets(java.nio.charset.StandardCharsets) Recycler(io.netty.util.Recycler) ManagedLedgerException(org.apache.bookkeeper.mledger.ManagedLedgerException) List(java.util.List) Slf4j(lombok.extern.slf4j.Slf4j) MemoryRecords(org.apache.kafka.common.record.MemoryRecords) Errors(org.apache.kafka.common.protocol.Errors) FetchRequest(org.apache.kafka.common.requests.FetchRequest) ConcurrentLinkedQueue(java.util.concurrent.ConcurrentLinkedQueue) AbstractResponse(org.apache.kafka.common.requests.AbstractResponse) Entry(org.apache.bookkeeper.mledger.Entry) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) CompletableFuture(java.util.concurrent.CompletableFuture) ArrayList(java.util.ArrayList) LinkedHashMap(java.util.LinkedHashMap) Resource(io.streamnative.pulsar.handlers.kop.security.auth.Resource) Lists(com.google.common.collect.Lists) GetResult(org.apache.pulsar.metadata.api.GetResult) THROTTLE_TIME_MS(org.apache.kafka.common.protocol.CommonFields.THROTTLE_TIME_MS) GroupIdUtils(io.streamnative.pulsar.handlers.kop.utils.GroupIdUtils) ManagedLedgerImpl(org.apache.bookkeeper.mledger.impl.ManagedLedgerImpl) DelayedOperation(io.streamnative.pulsar.handlers.kop.utils.delayed.DelayedOperation) KopTopic(io.streamnative.pulsar.handlers.kop.utils.KopTopic) ResourceType(io.streamnative.pulsar.handlers.kop.security.auth.ResourceType) MetadataCorruptedException(io.streamnative.pulsar.handlers.kop.exceptions.MetadataCorruptedException) KafkaHeaderAndRequest(io.streamnative.pulsar.handlers.kop.KafkaCommandDecoder.KafkaHeaderAndRequest) AclOperation(org.apache.kafka.common.acl.AclOperation) PartitionData(org.apache.kafka.common.requests.FetchResponse.PartitionData) TimeUnit(java.util.concurrent.TimeUnit) DecodeResult(io.streamnative.pulsar.handlers.kop.format.DecodeResult) AtomicLong(java.util.concurrent.atomic.AtomicLong) MarkDeleteCallback(org.apache.bookkeeper.mledger.AsyncCallbacks.MarkDeleteCallback) DelayedOperationKey(io.streamnative.pulsar.handlers.kop.utils.delayed.DelayedOperationKey) ReadEntriesCallback(org.apache.bookkeeper.mledger.AsyncCallbacks.ReadEntriesCallback) ApiException(org.apache.kafka.common.errors.ApiException) GetResult(org.apache.pulsar.metadata.api.GetResult) DecodeResult(io.streamnative.pulsar.handlers.kop.format.DecodeResult) Entry(org.apache.bookkeeper.mledger.Entry) CompletableFuture(java.util.concurrent.CompletableFuture) PartitionLog(io.streamnative.pulsar.handlers.kop.storage.PartitionLog) MemoryRecords(org.apache.kafka.common.record.MemoryRecords)

Aggregations

GetResult (org.apache.pulsar.metadata.api.GetResult)62 ExecutionException (java.util.concurrent.ExecutionException)24 Test (org.testng.annotations.Test)24 Optional (java.util.Optional)18 MetadataStore (org.apache.pulsar.metadata.api.MetadataStore)18 CompletableFuture (java.util.concurrent.CompletableFuture)17 ReplicationException (org.apache.bookkeeper.replication.ReplicationException)15 Cleanup (lombok.Cleanup)13 EnumSet (java.util.EnumSet)12 MetadataStoreException (org.apache.pulsar.metadata.api.MetadataStoreException)12 Stat (org.apache.pulsar.metadata.api.Stat)12 CreateOption (org.apache.pulsar.metadata.api.extended.CreateOption)12 List (java.util.List)11 TimeUnit (java.util.concurrent.TimeUnit)11 InvalidProtocolBufferException (com.google.protobuf.InvalidProtocolBufferException)9 Set (java.util.Set)9 CompletionException (java.util.concurrent.CompletionException)9 BeforeMethod (org.testng.annotations.BeforeMethod)9 Lists (com.google.common.collect.Lists)8 ArrayList (java.util.ArrayList)8