Search in sources :

Example 11 with GetResult

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

the class PulsarLedgerUnderreplicationManager method getLedgerUnreplicationInfo.

@Override
public UnderreplicatedLedger getLedgerUnreplicationInfo(long ledgerId) throws ReplicationException.UnavailableException {
    try {
        String path = getUrLedgerPath(ledgerId);
        Optional<GetResult> optRes = store.get(path).get();
        if (!optRes.isPresent()) {
            if (log.isDebugEnabled()) {
                log.debug("Ledger: {} is not marked underreplicated", ledgerId);
            }
            return null;
        }
        byte[] data = optRes.get().getValue();
        UnderreplicatedLedgerFormat.Builder builder = UnderreplicatedLedgerFormat.newBuilder();
        TextFormat.merge(new String(data, UTF_8), builder);
        UnderreplicatedLedgerFormat underreplicatedLedgerFormat = builder.build();
        PulsarUnderreplicatedLedger underreplicatedLedger = new PulsarUnderreplicatedLedger(ledgerId);
        List<String> replicaList = underreplicatedLedgerFormat.getReplicaList();
        long ctime = (underreplicatedLedgerFormat.hasCtime() ? underreplicatedLedgerFormat.getCtime() : UnderreplicatedLedger.UNASSIGNED_CTIME);
        underreplicatedLedger.setCtime(ctime);
        underreplicatedLedger.setReplicaList(replicaList);
        return underreplicatedLedger;
    } catch (ExecutionException ee) {
        throw new ReplicationException.UnavailableException("Error contacting with metadata store", ee);
    } catch (InterruptedException ie) {
        Thread.currentThread().interrupt();
        throw new ReplicationException.UnavailableException("Interrupted while connecting metadata store", ie);
    } catch (TextFormat.ParseException pe) {
        throw new ReplicationException.UnavailableException("Error parsing proto message", pe);
    }
}
Also used : GetResult(org.apache.pulsar.metadata.api.GetResult) TextFormat(com.google.protobuf.TextFormat) ReplicationException(org.apache.bookkeeper.replication.ReplicationException) ExecutionException(java.util.concurrent.ExecutionException) UnderreplicatedLedgerFormat(org.apache.bookkeeper.proto.DataFormats.UnderreplicatedLedgerFormat)

Example 12 with GetResult

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

the class NamespaceServiceTest method testUnloadNamespaceBundleWithStuckTopic.

/**
 * It verifies that unloading bundle will timeout and will not hung even if one of the topic-unloading stuck.
 *
 * @throws Exception
 */
@Test(timeOut = 6000)
public void testUnloadNamespaceBundleWithStuckTopic() throws Exception {
    final String topicName = "persistent://my-property/use/my-ns/my-topic1";
    Consumer<byte[]> consumer = 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);
    // return uncompleted future as close-topic result.
    doAnswer((Answer<CompletableFuture<Void>>) invocation -> new CompletableFuture<Void>()).when(spyTopic).close(false);
    NamespaceBundle bundle = pulsar.getNamespaceService().getBundle(TopicName.get(topicName));
    // try to unload bundle whose topic will be stuck
    pulsar.getNamespaceService().unloadNamespaceBundle(bundle, 1, TimeUnit.SECONDS).join();
    Optional<GetResult> res = this.pulsar.getLocalMetadataStore().get(ServiceUnitUtils.path(bundle)).join();
    assertFalse(res.isPresent());
    consumer.close();
}
Also used : BundleData(org.apache.pulsar.policies.data.loadbalancer.BundleData) Topic(org.apache.pulsar.broker.service.Topic) ObjectMapperFactory(org.apache.pulsar.common.util.ObjectMapperFactory) LoggerFactory(org.slf4j.LoggerFactory) Cleanup(lombok.Cleanup) 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) MetadataCache(org.apache.pulsar.metadata.api.MetadataCache) 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) Assert.assertNotEquals(org.testng.Assert.assertNotEquals) LoadData(org.apache.pulsar.broker.loadbalance.LoadData) 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) ServiceUnitId(org.apache.pulsar.common.naming.ServiceUnitId) 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) ResourceUnit(org.apache.pulsar.broker.loadbalance.ResourceUnit) Hashing(com.google.common.hash.Hashing) Mockito.spy(org.mockito.Mockito.spy) AtomicReference(java.util.concurrent.atomic.AtomicReference) 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) SimpleResourceUnit(org.apache.pulsar.broker.loadbalance.impl.SimpleResourceUnit) PulsarClient(org.apache.pulsar.client.api.PulsarClient) 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) 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 13 with GetResult

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

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 : BundleData(org.apache.pulsar.policies.data.loadbalancer.BundleData) Topic(org.apache.pulsar.broker.service.Topic) ObjectMapperFactory(org.apache.pulsar.common.util.ObjectMapperFactory) LoggerFactory(org.slf4j.LoggerFactory) Cleanup(lombok.Cleanup) 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) MetadataCache(org.apache.pulsar.metadata.api.MetadataCache) 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) Assert.assertNotEquals(org.testng.Assert.assertNotEquals) LoadData(org.apache.pulsar.broker.loadbalance.LoadData) 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) ServiceUnitId(org.apache.pulsar.common.naming.ServiceUnitId) 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) ResourceUnit(org.apache.pulsar.broker.loadbalance.ResourceUnit) Hashing(com.google.common.hash.Hashing) Mockito.spy(org.mockito.Mockito.spy) AtomicReference(java.util.concurrent.atomic.AtomicReference) 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) SimpleResourceUnit(org.apache.pulsar.broker.loadbalance.impl.SimpleResourceUnit) PulsarClient(org.apache.pulsar.client.api.PulsarClient) 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) 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 14 with GetResult

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

the class MetadataStoreBatchingTest method testBatching.

@Test(dataProvider = "impl")
public void testBatching(String provider, Supplier<String> urlSupplier) throws Exception {
    @Cleanup MetadataStore store = MetadataStoreFactory.create(urlSupplier.get(), MetadataStoreConfig.builder().batchingEnabled(true).batchingMaxDelayMillis(1_000).build());
    String key1 = newKey();
    store.put(key1, new byte[0], Optional.empty()).join();
    String key2 = newKey();
    CompletableFuture<Optional<GetResult>> f1 = store.get(key1);
    CompletableFuture<Optional<GetResult>> f2 = store.get(key2);
    Optional<GetResult> r1 = f1.join();
    Optional<GetResult> r2 = f2.join();
    assertTrue(r1.isPresent());
    assertFalse(r2.isPresent());
}
Also used : MetadataStore(org.apache.pulsar.metadata.api.MetadataStore) Optional(java.util.Optional) GetResult(org.apache.pulsar.metadata.api.GetResult) Cleanup(lombok.Cleanup) Test(org.testng.annotations.Test)

Example 15 with GetResult

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

the class MetadataStoreTest method testConcurrentPutGetOneKey.

@Test(dataProvider = "impl")
public void testConcurrentPutGetOneKey(String provider, Supplier<String> urlSupplier) throws Exception {
    MetadataStore store = MetadataStoreFactory.create(urlSupplier.get(), MetadataStoreConfig.builder().build());
    byte[] data = new byte[] { 0 };
    String path = newKey();
    int maxValue = 100;
    store.put(path, data, Optional.of(-1L)).join();
    AtomicInteger successWrites = new AtomicInteger(0);
    Runnable task = new Runnable() {

        @SneakyThrows
        @Override
        public void run() {
            byte value;
            while (true) {
                GetResult readResult = store.get(path).get().get();
                value = (byte) (readResult.getValue()[0] + 1);
                if (value <= maxValue) {
                    CompletableFuture<Void> putResult = store.put(path, new byte[] { value }, Optional.of(readResult.getStat().getVersion())).thenRun(successWrites::incrementAndGet);
                    try {
                        putResult.get();
                    } catch (Exception ignore) {
                    }
                    log.info("Put value {} success:{}. ", value, !putResult.isCompletedExceptionally());
                } else {
                    break;
                }
            }
        }
    };
    CompletableFuture<Void> t1 = CompletableFuture.completedFuture(null).thenRunAsync(task);
    CompletableFuture<Void> t2 = CompletableFuture.completedFuture(null).thenRunAsync(task);
    task.run();
    t1.join();
    t2.join();
    assertFalse(t1.isCompletedExceptionally());
    assertFalse(t2.isCompletedExceptionally());
    assertEquals(successWrites.get(), maxValue);
    assertEquals(store.get(path).get().get().getValue()[0], maxValue);
}
Also used : MetadataStore(org.apache.pulsar.metadata.api.MetadataStore) GetResult(org.apache.pulsar.metadata.api.GetResult) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) MetadataStoreException(org.apache.pulsar.metadata.api.MetadataStoreException) CompletionException(java.util.concurrent.CompletionException) NotFoundException(org.apache.pulsar.metadata.api.MetadataStoreException.NotFoundException) BadVersionException(org.apache.pulsar.metadata.api.MetadataStoreException.BadVersionException) Test(org.testng.annotations.Test)

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