Search in sources :

Example 36 with PulsarClientException

use of org.apache.pulsar.client.api.PulsarClientException in project flink by apache.

the class PulsarRuntimeOperator method createConsumer.

@SuppressWarnings("unchecked")
private <T> Consumer<T> createConsumer(String topic, Schema<T> schema) throws PulsarClientException {
    TopicName topicName = TopicName.get(topic);
    String name = topicName.getPartitionedTopicName();
    int index = topicName.getPartitionIndex();
    ConcurrentHashMap<Integer, Consumer<?>> topicConsumers = consumers.computeIfAbsent(name, d -> new ConcurrentHashMap<>());
    return (Consumer<T>) topicConsumers.computeIfAbsent(index, i -> {
        try {
            return client().newConsumer(schema).topic(topic).subscriptionName(SUBSCRIPTION_NAME).subscriptionMode(Durable).subscriptionType(Exclusive).subscriptionInitialPosition(SubscriptionInitialPosition.Earliest).subscribe();
        } catch (PulsarClientException e) {
            sneakyThrow(e);
            return null;
        }
    });
}
Also used : Strings(org.apache.flink.shaded.guava30.com.google.common.base.Strings) Arrays(java.util.Arrays) Durable(org.apache.pulsar.client.api.SubscriptionMode.Durable) PulsarClientImpl(org.apache.pulsar.client.impl.PulsarClientImpl) PulsarExceptionUtils.sneakyAdmin(org.apache.flink.connector.pulsar.common.utils.PulsarExceptionUtils.sneakyAdmin) Producer(org.apache.pulsar.client.api.Producer) EXACTLY_ONCE(org.apache.flink.connector.base.DeliveryGuarantee.EXACTLY_ONCE) NotFoundException(org.apache.pulsar.client.admin.PulsarAdminException.NotFoundException) Random(java.util.Random) Collections.singletonList(java.util.Collections.singletonList) TxnID(org.apache.pulsar.client.api.transaction.TxnID) Collectors.toMap(java.util.stream.Collectors.toMap) Duration(java.time.Duration) Map(java.util.Map) PulsarClientException(org.apache.pulsar.client.api.PulsarClientException) ExternalContext(org.apache.flink.connector.testframe.external.ExternalContext) Collections.emptyList(java.util.Collections.emptyList) Collection(java.util.Collection) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) MILLISECONDS(java.util.concurrent.TimeUnit.MILLISECONDS) PulsarExceptionUtils.sneakyClient(org.apache.flink.connector.pulsar.common.utils.PulsarExceptionUtils.sneakyClient) Consumer(org.apache.pulsar.client.api.Consumer) List(java.util.List) Stream(java.util.stream.Stream) Preconditions.checkArgument(org.apache.flink.util.Preconditions.checkArgument) RandomStringUtils.randomAlphanumeric(org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric) Function.identity(java.util.function.Function.identity) PULSAR_ADMIN_URL(org.apache.flink.connector.pulsar.common.config.PulsarOptions.PULSAR_ADMIN_URL) PulsarExceptionUtils.sneakyThrow(org.apache.flink.connector.pulsar.common.utils.PulsarExceptionUtils.sneakyThrow) PULSAR_ENABLE_TRANSACTION(org.apache.flink.connector.pulsar.common.config.PulsarOptions.PULSAR_ENABLE_TRANSACTION) DeliveryGuarantee(org.apache.flink.connector.base.DeliveryGuarantee) TopicName(org.apache.pulsar.common.naming.TopicName) TopicRange(org.apache.flink.connector.pulsar.source.enumerator.topic.TopicRange) PulsarAdmin(org.apache.pulsar.client.admin.PulsarAdmin) Message(org.apache.pulsar.client.api.Message) PartitionedTopicMetadata(org.apache.pulsar.common.partition.PartitionedTopicMetadata) SubscriptionInitialPosition(org.apache.pulsar.client.api.SubscriptionInitialPosition) Supplier(java.util.function.Supplier) TransactionCoordinatorClient(org.apache.pulsar.client.api.transaction.TransactionCoordinatorClient) ArrayList(java.util.ArrayList) Exclusive(org.apache.pulsar.client.api.SubscriptionType.Exclusive) PULSAR_WRITE_TRANSACTION_TIMEOUT(org.apache.flink.connector.pulsar.sink.PulsarSinkOptions.PULSAR_WRITE_TRANSACTION_TIMEOUT) PulsarClient(org.apache.pulsar.client.api.PulsarClient) TypedMessageBuilder(org.apache.pulsar.client.api.TypedMessageBuilder) PULSAR_SEND_TIMEOUT_MS(org.apache.flink.connector.pulsar.sink.PulsarSinkOptions.PULSAR_SEND_TIMEOUT_MS) TopicNameUtils.topicName(org.apache.flink.connector.pulsar.source.enumerator.topic.TopicNameUtils.topicName) PulsarAdminException(org.apache.pulsar.client.admin.PulsarAdminException) Configuration(org.apache.flink.configuration.Configuration) IOException(java.io.IOException) TopicPartition(org.apache.flink.connector.pulsar.source.enumerator.topic.TopicPartition) Schema(org.apache.pulsar.client.api.Schema) ExecutionException(java.util.concurrent.ExecutionException) PulsarConfiguration(org.apache.flink.connector.pulsar.common.config.PulsarConfiguration) Collectors.toList(java.util.stream.Collectors.toList) MessageId(org.apache.pulsar.client.api.MessageId) PULSAR_WRITE_DELIVERY_GUARANTEE(org.apache.flink.connector.pulsar.sink.PulsarSinkOptions.PULSAR_WRITE_DELIVERY_GUARANTEE) Closeable(java.io.Closeable) TopicNameUtils.topicNameWithPartition(org.apache.flink.connector.pulsar.source.enumerator.topic.TopicNameUtils.topicNameWithPartition) PULSAR_SERVICE_URL(org.apache.flink.connector.pulsar.common.config.PulsarOptions.PULSAR_SERVICE_URL) Consumer(org.apache.pulsar.client.api.Consumer) PulsarClientException(org.apache.pulsar.client.api.PulsarClientException) TopicName(org.apache.pulsar.common.naming.TopicName)

Example 37 with PulsarClientException

use of org.apache.pulsar.client.api.PulsarClientException in project flink by apache.

the class PulsarPartitionSplitReaderTestBase method seekStartPositionAndHandleSplit.

private void seekStartPositionAndHandleSplit(PulsarPartitionSplitReaderBase<String> reader, String topicName, int partitionId, MessageId startPosition) {
    TopicPartition partition = new TopicPartition(topicName, partitionId, createFullRange());
    PulsarPartitionSplit split = new PulsarPartitionSplit(partition, StopCursor.never(), null, null);
    SplitsAddition<PulsarPartitionSplit> addition = new SplitsAddition<>(singletonList(split));
    // create consumer and seek before split changes
    try (Consumer<byte[]> consumer = reader.createPulsarConsumer(partition)) {
        // inclusive messageId
        StartCursor startCursor = StartCursor.fromMessageId(startPosition);
        startCursor.seekPosition(partition.getTopic(), partition.getPartitionId(), consumer);
    } catch (PulsarClientException e) {
        sneakyThrow(e);
    }
    reader.handleSplitsChanges(addition);
}
Also used : TopicPartition(org.apache.flink.connector.pulsar.source.enumerator.topic.TopicPartition) StartCursor(org.apache.flink.connector.pulsar.source.enumerator.cursor.StartCursor) SplitsAddition(org.apache.flink.connector.base.source.reader.splitreader.SplitsAddition) PulsarClientException(org.apache.pulsar.client.api.PulsarClientException) PulsarPartitionSplit(org.apache.flink.connector.pulsar.source.split.PulsarPartitionSplit)

Example 38 with PulsarClientException

use of org.apache.pulsar.client.api.PulsarClientException in project incubator-pulsar by apache.

the class ContextImpl method publish.

@Override
public <O> CompletableFuture<Void> publish(String topicName, O object, String serDeClassName) {
    if (!publishProducers.containsKey(topicName)) {
        try {
            publishProducers.put(topicName, pulsarClient.createProducer(topicName, producerConfiguration));
        } catch (PulsarClientException ex) {
            CompletableFuture<Void> retval = new CompletableFuture<>();
            retval.completeExceptionally(ex);
            return retval;
        }
    }
    if (!publishSerializers.containsKey(serDeClassName)) {
        SerDe serDe;
        if (serDeClassName.equals(DefaultSerDe.class.getName())) {
            if (!DefaultSerDe.IsSupportedType(object.getClass())) {
                throw new RuntimeException("Default Serializer does not support " + object.getClass());
            }
            serDe = new DefaultSerDe(object.getClass());
        } else {
            try {
                Class<? extends SerDe> serDeClass = (Class<? extends SerDe>) Class.forName(serDeClassName);
                serDe = Reflections.createInstance(serDeClassName, serDeClass, classLoader);
            } catch (ClassNotFoundException e) {
                throw new RuntimeException(e);
            }
        }
        publishSerializers.put(serDeClassName, serDe);
    }
    byte[] bytes = publishSerializers.get(serDeClassName).serialize(object);
    return publishProducers.get(topicName).sendAsync(bytes).thenApply(msgId -> null);
}
Also used : DefaultSerDe(org.apache.pulsar.functions.api.utils.DefaultSerDe) SerDe(org.apache.pulsar.functions.api.SerDe) CompletableFuture(java.util.concurrent.CompletableFuture) PulsarClientException(org.apache.pulsar.client.api.PulsarClientException) DefaultSerDe(org.apache.pulsar.functions.api.utils.DefaultSerDe)

Example 39 with PulsarClientException

use of org.apache.pulsar.client.api.PulsarClientException in project incubator-pulsar by apache.

the class ConsumerImpl method unsubscribeAsync.

@Override
public CompletableFuture<Void> unsubscribeAsync() {
    if (getState() == State.Closing || getState() == State.Closed) {
        return FutureUtil.failedFuture(new PulsarClientException.AlreadyClosedException("Consumer was already closed"));
    }
    final CompletableFuture<Void> unsubscribeFuture = new CompletableFuture<>();
    if (isConnected()) {
        setState(State.Closing);
        long requestId = client.newRequestId();
        ByteBuf unsubscribe = Commands.newUnsubscribe(consumerId, requestId);
        ClientCnx cnx = cnx();
        cnx.sendRequestWithId(unsubscribe, requestId).thenRun(() -> {
            cnx.removeConsumer(consumerId);
            log.info("[{}][{}] Successfully unsubscribed from topic", topic, subscription);
            unAckedMessageTracker.close();
            unsubscribeFuture.complete(null);
            setState(State.Closed);
        }).exceptionally(e -> {
            log.error("[{}][{}] Failed to unsubscribe: {}", topic, subscription, e.getCause().getMessage());
            unsubscribeFuture.completeExceptionally(e.getCause());
            setState(State.Ready);
            return null;
        });
    } else {
        unsubscribeFuture.completeExceptionally(new PulsarClientException("Not connected to broker"));
    }
    return unsubscribeFuture;
}
Also used : CompletableFuture(java.util.concurrent.CompletableFuture) PulsarClientException(org.apache.pulsar.client.api.PulsarClientException) ByteBuf(io.netty.buffer.ByteBuf)

Example 40 with PulsarClientException

use of org.apache.pulsar.client.api.PulsarClientException in project incubator-pulsar by apache.

the class ConsumerImpl method fetchSingleMessageFromBroker.

private Message<T> fetchSingleMessageFromBroker() throws PulsarClientException {
    checkArgument(conf.getReceiverQueueSize() == 0);
    // Just being cautious
    if (incomingMessages.size() > 0) {
        log.error("The incoming message queue should never be greater than 0 when Queue size is 0");
        incomingMessages.clear();
    }
    Message<T> message;
    try {
        // is cnx is null or if the connection breaks the connectionOpened function will send the flow again
        waitingOnReceiveForZeroQueueSize = true;
        synchronized (this) {
            if (isConnected()) {
                sendFlowPermitsToBroker(cnx(), 1);
            }
        }
        do {
            message = incomingMessages.take();
            lastDequeuedMessage = message.getMessageId();
            ClientCnx msgCnx = ((MessageImpl<?>) message).getCnx();
            // synchronized need to prevent race between connectionOpened and the check "msgCnx == cnx()"
            synchronized (ConsumerImpl.this) {
                // latest flow command
                if (msgCnx == cnx()) {
                    waitingOnReceiveForZeroQueueSize = false;
                    break;
                }
            }
        } while (true);
        stats.updateNumMsgsReceived(message);
        return message;
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
        stats.incrementNumReceiveFailed();
        throw new PulsarClientException(e);
    } finally {
        // Finally blocked is invoked in case the block on incomingMessages is interrupted
        waitingOnReceiveForZeroQueueSize = false;
        // Clearing the queue in case there was a race with messageReceived
        incomingMessages.clear();
    }
}
Also used : PulsarClientException(org.apache.pulsar.client.api.PulsarClientException)

Aggregations

PulsarClientException (org.apache.pulsar.client.api.PulsarClientException)65 Test (org.testng.annotations.Test)24 CompletableFuture (java.util.concurrent.CompletableFuture)17 Message (org.apache.pulsar.client.api.Message)15 IOException (java.io.IOException)14 PulsarClient (org.apache.pulsar.client.api.PulsarClient)13 ExecutionException (java.util.concurrent.ExecutionException)12 Consumer (org.apache.pulsar.client.api.Consumer)12 MessageId (org.apache.pulsar.client.api.MessageId)12 Producer (org.apache.pulsar.client.api.Producer)12 ByteBuf (io.netty.buffer.ByteBuf)11 List (java.util.List)8 ConsumerConfiguration (org.apache.pulsar.client.api.ConsumerConfiguration)8 ProducerConfiguration (org.apache.pulsar.client.api.ProducerConfiguration)7 ArrayList (java.util.ArrayList)6 HashSet (java.util.HashSet)6 Map (java.util.Map)6 Logger (org.slf4j.Logger)6 LoggerFactory (org.slf4j.LoggerFactory)6 TimeUnit (java.util.concurrent.TimeUnit)5