Search in sources :

Example 6 with Message

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

the class FunctionMetaDataTopicTailerTest method testUpdate.

@Test
public void testUpdate() throws Exception {
    ServiceRequest request = ServiceRequestUtils.getUpdateRequest(TEST_NAME, FunctionMetaData.newBuilder().build());
    Message msg = mock(Message.class);
    when(msg.getData()).thenReturn(request.toByteArray());
    CompletableFuture<Message> receiveFuture = CompletableFuture.completedFuture(msg);
    when(reader.readNextAsync()).thenReturn(receiveFuture).thenReturn(new CompletableFuture<>());
    fsc.start();
    // wait for receive future to complete
    receiveFuture.thenApply(Function.identity()).get();
    verify(reader, times(2)).readNextAsync();
    verify(fsm, times(1)).processRequest(any(MessageId.class), any(ServiceRequest.class));
}
Also used : Message(org.apache.pulsar.client.api.Message) ServiceRequest(org.apache.pulsar.functions.proto.Request.ServiceRequest) MessageId(org.apache.pulsar.client.api.MessageId) Test(org.testng.annotations.Test)

Example 7 with Message

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

the class FunctionsImpl method triggerFunction.

@POST
@Path("/{tenant}/{namespace}/{functionName}/trigger")
@Consumes(MediaType.MULTIPART_FORM_DATA)
public Response triggerFunction(@PathParam("tenant") final String tenant, @PathParam("namespace") final String namespace, @PathParam("name") final String functionName, @FormDataParam("data") final String input, @FormDataParam("dataStream") final InputStream uploadedInputStream) {
    FunctionConfig functionConfig;
    // validate parameters
    try {
        validateTriggerRequestParams(tenant, namespace, functionName, input, uploadedInputStream);
    } catch (IllegalArgumentException e) {
        log.error("Invalid trigger function request @ /{}/{}/{}", tenant, namespace, functionName, e);
        return Response.status(Status.BAD_REQUEST).type(MediaType.APPLICATION_JSON).entity(new ErrorData(e.getMessage())).build();
    }
    FunctionMetaDataManager functionMetaDataManager = worker().getFunctionMetaDataManager();
    if (!functionMetaDataManager.containsFunction(tenant, namespace, functionName)) {
        log.error("Function in getFunction does not exist @ /{}/{}/{}", tenant, namespace, functionName);
        return Response.status(Status.NOT_FOUND).type(MediaType.APPLICATION_JSON).entity(new ErrorData(String.format("Function %s doesn't exist", functionName))).build();
    }
    FunctionMetaData functionMetaData = functionMetaDataManager.getFunctionMetaData(tenant, namespace, functionName);
    String inputTopicToWrite;
    if (functionMetaData.getFunctionConfig().getInputsList().size() > 0) {
        inputTopicToWrite = functionMetaData.getFunctionConfig().getInputsList().get(0);
    } else {
        inputTopicToWrite = functionMetaData.getFunctionConfig().getCustomSerdeInputs().entrySet().iterator().next().getKey();
    }
    String outputTopic = functionMetaData.getFunctionConfig().getOutput();
    Reader reader = null;
    Producer producer = null;
    try {
        if (outputTopic != null && !outputTopic.isEmpty()) {
            reader = worker().getClient().newReader().topic(outputTopic).startMessageId(MessageId.latest).create();
        }
        producer = worker().getClient().newProducer().topic(inputTopicToWrite).create();
        byte[] targetArray;
        if (uploadedInputStream != null) {
            targetArray = new byte[uploadedInputStream.available()];
            uploadedInputStream.read(targetArray);
        } else {
            targetArray = input.getBytes();
        }
        MessageId msgId = producer.send(targetArray);
        if (reader == null) {
            return Response.status(Status.OK).build();
        }
        long curTime = System.currentTimeMillis();
        long maxTime = curTime + 1000;
        while (curTime < maxTime) {
            Message msg = reader.readNext(10000, TimeUnit.MILLISECONDS);
            if (msg == null)
                break;
            if (msg.getProperties().containsKey("__pfn_input_msg_id__") && msg.getProperties().containsKey("__pfn_input_topic__")) {
                MessageId newMsgId = MessageId.fromByteArray(Base64.getDecoder().decode((String) msg.getProperties().get("__pfn_input_msg_id__")));
                if (msgId.equals(newMsgId) && msg.getProperties().get("__pfn_input_topic__").equals(inputTopicToWrite)) {
                    return Response.status(Status.OK).entity(msg.getData()).build();
                }
            }
            curTime = System.currentTimeMillis();
        }
        return Response.status(Status.REQUEST_TIMEOUT).build();
    } catch (Exception e) {
        return Response.status(Status.INTERNAL_SERVER_ERROR).build();
    } finally {
        if (reader != null) {
            reader.closeAsync();
        }
        if (producer != null) {
            producer.closeAsync();
        }
    }
}
Also used : FunctionConfig(org.apache.pulsar.functions.proto.Function.FunctionConfig) FunctionMetaData(org.apache.pulsar.functions.proto.Function.FunctionMetaData) Message(org.apache.pulsar.client.api.Message) Reader(org.apache.pulsar.client.api.Reader) IOException(java.io.IOException) ExecutionException(java.util.concurrent.ExecutionException) Producer(org.apache.pulsar.client.api.Producer) FunctionMetaDataManager(org.apache.pulsar.functions.worker.FunctionMetaDataManager) ErrorData(org.apache.pulsar.common.policies.data.ErrorData) MessageId(org.apache.pulsar.client.api.MessageId) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST) Consumes(javax.ws.rs.Consumes)

Example 8 with Message

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

the class ConsumerImpl method internalGetLastMessageIdAsync.

private void internalGetLastMessageIdAsync(final Backoff backoff, final AtomicLong remainingTime, CompletableFuture<MessageId> future) {
    ClientCnx cnx = cnx();
    if (isConnected() && cnx != null) {
        if (!Commands.peerSupportsGetLastMessageId(cnx.getRemoteEndpointProtocolVersion())) {
            future.completeExceptionally(new PulsarClientException.NotSupportedException("GetLastMessageId Not supported for ProtocolVersion: " + cnx.getRemoteEndpointProtocolVersion()));
        }
        long requestId = client.newRequestId();
        ByteBuf getLastIdCmd = Commands.newGetLastMessageId(consumerId, requestId);
        log.info("[{}][{}] Get topic last message Id", topic, subscription);
        cnx.sendGetLastMessageId(getLastIdCmd, requestId).thenAccept((result) -> {
            log.info("[{}][{}] Successfully getLastMessageId {}:{}", topic, subscription, result.getLedgerId(), result.getEntryId());
            future.complete(new MessageIdImpl(result.getLedgerId(), result.getEntryId(), result.getPartition()));
        }).exceptionally(e -> {
            log.error("[{}][{}] Failed getLastMessageId command", topic, subscription);
            future.completeExceptionally(e.getCause());
            return null;
        });
    } else {
        long nextDelay = Math.min(backoff.next(), remainingTime.get());
        if (nextDelay <= 0) {
            future.completeExceptionally(new PulsarClientException.TimeoutException("Could not getLastMessageId within configured timeout."));
            return;
        }
        ((ScheduledExecutorService) listenerExecutor).schedule(() -> {
            log.warn("[{}] [{}] Could not get connection while getLastMessageId -- Will try again in {} ms", topic, getHandlerName(), nextDelay);
            remainingTime.addAndGet(-nextDelay);
            internalGetLastMessageIdAsync(backoff, remainingTime, future);
        }, nextDelay, TimeUnit.MILLISECONDS);
    }
}
Also used : PulsarApi(org.apache.pulsar.common.api.proto.PulsarApi) Commands.hasChecksum(org.apache.pulsar.common.api.Commands.hasChecksum) LoggerFactory(org.slf4j.LoggerFactory) AckType(org.apache.pulsar.common.api.proto.PulsarApi.CommandAck.AckType) Preconditions.checkArgument(com.google.common.base.Preconditions.checkArgument) Map(java.util.Map) PulsarClientException(org.apache.pulsar.client.api.PulsarClientException) Crc32cIntChecksum.computeChecksum(com.scurrilous.circe.checksum.Crc32cIntChecksum.computeChecksum) ReadWriteLock(java.util.concurrent.locks.ReadWriteLock) PulsarDecoder(org.apache.pulsar.common.api.PulsarDecoder) Commands(org.apache.pulsar.common.api.Commands) Set(java.util.Set) Collectors(java.util.stream.Collectors) String.format(java.lang.String.format) Objects(java.util.Objects) Consumer(org.apache.pulsar.client.api.Consumer) List(java.util.List) FutureUtil(org.apache.pulsar.common.util.FutureUtil) MessageIdData(org.apache.pulsar.common.api.proto.PulsarApi.MessageIdData) CompressionCodec(org.apache.pulsar.common.compression.CompressionCodec) AtomicIntegerFieldUpdater(java.util.concurrent.atomic.AtomicIntegerFieldUpdater) ConsumerCryptoFailureAction(org.apache.pulsar.client.api.ConsumerCryptoFailureAction) Iterables(com.google.common.collect.Iterables) ConsumerConfigurationData(org.apache.pulsar.client.impl.conf.ConsumerConfigurationData) HashMap(java.util.HashMap) CompletableFuture(java.util.concurrent.CompletableFuture) ProtocolVersion(org.apache.pulsar.common.api.proto.PulsarApi.ProtocolVersion) ReentrantReadWriteLock(java.util.concurrent.locks.ReentrantReadWriteLock) Message(org.apache.pulsar.client.api.Message) SubscriptionInitialPosition(org.apache.pulsar.client.api.SubscriptionInitialPosition) ArrayList(java.util.ArrayList) ConsumerStats(org.apache.pulsar.client.api.ConsumerStats) ByteBuf(io.netty.buffer.ByteBuf) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) CompressionCodecProvider(org.apache.pulsar.common.compression.CompressionCodecProvider) MessageMetadata(org.apache.pulsar.common.api.proto.PulsarApi.MessageMetadata) ExecutorService(java.util.concurrent.ExecutorService) Timeout(io.netty.util.Timeout) Logger(org.slf4j.Logger) Preconditions.checkNotNull(com.google.common.base.Preconditions.checkNotNull) GenericFutureListener(io.netty.util.concurrent.GenericFutureListener) IOException(java.io.IOException) SubscriptionType(org.apache.pulsar.client.api.SubscriptionType) Schema(org.apache.pulsar.client.api.Schema) Commands.readChecksum(org.apache.pulsar.common.api.Commands.readChecksum) ExecutionException(java.util.concurrent.ExecutionException) TimeUnit(java.util.concurrent.TimeUnit) ValidationError(org.apache.pulsar.common.api.proto.PulsarApi.CommandAck.ValidationError) AtomicLong(java.util.concurrent.atomic.AtomicLong) MessageId(org.apache.pulsar.client.api.MessageId) CompressionType(org.apache.pulsar.common.api.proto.PulsarApi.CompressionType) InitialPosition(org.apache.pulsar.common.api.proto.PulsarApi.CommandSubscribe.InitialPosition) Future(io.netty.util.concurrent.Future) Collections(java.util.Collections) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) PulsarClientException(org.apache.pulsar.client.api.PulsarClientException) ByteBuf(io.netty.buffer.ByteBuf)

Example 9 with Message

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

the class ProducerImpl method connectionOpened.

@Override
public void connectionOpened(final ClientCnx cnx) {
    // we set the cnx reference before registering the producer on the cnx, so if the cnx breaks before creating the
    // producer, it will try to grab a new cnx
    connectionHandler.setClientCnx(cnx);
    cnx.registerProducer(producerId, this);
    log.info("[{}] [{}] Creating producer on cnx {}", topic, producerName, cnx.ctx().channel());
    long requestId = client.newRequestId();
    cnx.sendRequestWithId(Commands.newProducer(topic, producerId, requestId, producerName, conf.isEncryptionEnabled(), metadata), requestId).thenAccept(pair -> {
        String producerName = pair.getLeft();
        long lastSequenceId = pair.getRight();
        // set the cnx pointer so that new messages will be sent immediately
        synchronized (ProducerImpl.this) {
            if (getState() == State.Closing || getState() == State.Closed) {
                // Producer was closed while reconnecting, close the connection to make sure the broker
                // drops the producer on its side
                cnx.removeProducer(producerId);
                cnx.channel().close();
                return;
            }
            resetBackoff();
            log.info("[{}] [{}] Created producer on cnx {}", topic, producerName, cnx.ctx().channel());
            connectionId = cnx.ctx().channel().toString();
            connectedSince = DateFormatter.now();
            if (this.producerName == null) {
                this.producerName = producerName;
            }
            if (this.lastSequenceIdPublished == -1 && conf.getInitialSequenceId() == null) {
                this.lastSequenceIdPublished = lastSequenceId;
                this.msgIdGenerator = lastSequenceId + 1;
            }
            if (!producerCreatedFuture.isDone() && isBatchMessagingEnabled()) {
                // schedule the first batch message task
                client.timer().newTimeout(batchMessageAndSendTask, conf.getBatchingMaxPublishDelayMicros(), TimeUnit.MICROSECONDS);
            }
            resendMessages(cnx);
        }
    }).exceptionally((e) -> {
        Throwable cause = e.getCause();
        cnx.removeProducer(producerId);
        if (getState() == State.Closing || getState() == State.Closed) {
            // Producer was closed while reconnecting, close the connection to make sure the broker
            // drops the producer on its side
            cnx.channel().close();
            return null;
        }
        log.error("[{}] [{}] Failed to create producer: {}", topic, producerName, cause.getMessage());
        if (cause instanceof PulsarClientException.ProducerBlockedQuotaExceededException) {
            synchronized (this) {
                log.warn("[{}] [{}] Topic backlog quota exceeded. Throwing Exception on producer.", topic, producerName);
                if (log.isDebugEnabled()) {
                    log.debug("[{}] [{}] Pending messages: {}", topic, producerName, pendingMessages.size());
                }
                PulsarClientException bqe = new PulsarClientException.ProducerBlockedQuotaExceededException("Could not send pending messages as backlog exceeded");
                failPendingMessages(cnx(), bqe);
            }
        } else if (cause instanceof PulsarClientException.ProducerBlockedQuotaExceededError) {
            log.warn("[{}] [{}] Producer is blocked on creation because backlog exceeded on topic.", producerName, topic);
        }
        if (cause instanceof PulsarClientException.TopicTerminatedException) {
            setState(State.Terminated);
            failPendingMessages(cnx(), (PulsarClientException) cause);
            producerCreatedFuture.completeExceptionally(cause);
            client.cleanupProducer(this);
        } else if (// 
        producerCreatedFuture.isDone() || (cause instanceof PulsarClientException && connectionHandler.isRetriableError((PulsarClientException) cause) && System.currentTimeMillis() < createProducerTimeout)) {
            // Either we had already created the producer once (producerCreatedFuture.isDone()) or we are
            // still within the initial timeout budget and we are dealing with a retriable error
            reconnectLater(cause);
        } else {
            setState(State.Failed);
            producerCreatedFuture.completeExceptionally(cause);
            client.cleanupProducer(this);
        }
        return null;
    });
}
Also used : PulsarApi(org.apache.pulsar.common.api.proto.PulsarApi) CompressionCodec(org.apache.pulsar.common.compression.CompressionCodec) Commands.hasChecksum(org.apache.pulsar.common.api.Commands.hasChecksum) ByteBufPair(org.apache.pulsar.common.api.ByteBufPair) ScheduledFuture(io.netty.util.concurrent.ScheduledFuture) Producer(org.apache.pulsar.client.api.Producer) LoggerFactory(org.slf4j.LoggerFactory) HashMap(java.util.HashMap) CompletableFuture(java.util.concurrent.CompletableFuture) ProtocolVersion(org.apache.pulsar.common.api.proto.PulsarApi.ProtocolVersion) Message(org.apache.pulsar.client.api.Message) ChecksumType(org.apache.pulsar.common.api.Commands.ChecksumType) Preconditions.checkArgument(com.google.common.base.Preconditions.checkArgument) DateFormatter(org.apache.pulsar.common.util.DateFormatter) ByteBuf(io.netty.buffer.ByteBuf) Handle(io.netty.util.Recycler.Handle) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Map(java.util.Map) CompressionCodecProvider(org.apache.pulsar.common.compression.CompressionCodecProvider) TimerTask(io.netty.util.TimerTask) MessageMetadata(org.apache.pulsar.common.api.proto.PulsarApi.MessageMetadata) Crc32cIntChecksum.resumeChecksum(com.scurrilous.circe.checksum.Crc32cIntChecksum.resumeChecksum) PulsarClientException(org.apache.pulsar.client.api.PulsarClientException) Crc32cIntChecksum.computeChecksum(com.scurrilous.circe.checksum.Crc32cIntChecksum.computeChecksum) PulsarDecoder(org.apache.pulsar.common.api.PulsarDecoder) CryptoException(org.apache.pulsar.client.api.PulsarClientException.CryptoException) Commands(org.apache.pulsar.common.api.Commands) Timeout(io.netty.util.Timeout) Logger(org.slf4j.Logger) Semaphore(java.util.concurrent.Semaphore) CompressionType(org.apache.pulsar.client.api.CompressionType) ProducerCryptoFailureAction(org.apache.pulsar.client.api.ProducerCryptoFailureAction) IOException(java.io.IOException) BlockingQueue(java.util.concurrent.BlockingQueue) AtomicLongFieldUpdater(java.util.concurrent.atomic.AtomicLongFieldUpdater) String.format(java.lang.String.format) ProducerConfigurationData(org.apache.pulsar.client.impl.conf.ProducerConfigurationData) Schema(org.apache.pulsar.client.api.Schema) Recycler(io.netty.util.Recycler) Commands.readChecksum(org.apache.pulsar.common.api.Commands.readChecksum) ExecutionException(java.util.concurrent.ExecutionException) TimeUnit(java.util.concurrent.TimeUnit) List(java.util.List) Queues(com.google.common.collect.Queues) MessageId(org.apache.pulsar.client.api.MessageId) ReferenceCountUtil(io.netty.util.ReferenceCountUtil) Collections(java.util.Collections) PulsarClientException(org.apache.pulsar.client.api.PulsarClientException)

Example 10 with Message

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

the class PulsarBoltTest method testMetrics.

@Test
public void testMetrics() throws Exception {
    bolt.resetMetrics();
    String msgContent = "hello world";
    Tuple tuple = getMockTuple(msgContent);
    for (int i = 0; i < 10; i++) {
        bolt.execute(tuple);
    }
    for (int i = 0; i < NO_OF_RETRIES; i++) {
        Thread.sleep(1000);
        if (mockCollector.getNumTuplesAcked() == 10) {
            break;
        }
    }
    @SuppressWarnings("rawtypes") Map metrics = (Map) bolt.getValueAndReset();
    Assert.assertEquals(((Long) metrics.get(PulsarBolt.NO_OF_MESSAGES_SENT)).longValue(), 10);
    Assert.assertEquals(((Double) metrics.get(PulsarBolt.PRODUCER_RATE)).doubleValue(), 10.0 / pulsarBoltConf.getMetricsTimeIntervalInSecs());
    Assert.assertEquals(((Double) metrics.get(PulsarBolt.PRODUCER_THROUGHPUT_BYTES)).doubleValue(), ((double) msgContent.getBytes().length * 10) / pulsarBoltConf.getMetricsTimeIntervalInSecs());
    metrics = bolt.getMetrics();
    Assert.assertEquals(((Long) metrics.get(PulsarBolt.NO_OF_MESSAGES_SENT)).longValue(), 0);
    for (int i = 0; i < 10; i++) {
        Message msg = consumer.receive(5, TimeUnit.SECONDS);
        consumer.acknowledge(msg);
    }
}
Also used : Message(org.apache.pulsar.client.api.Message) Map(java.util.Map) Tuple(org.apache.storm.tuple.Tuple) Test(org.testng.annotations.Test)

Aggregations

Message (org.apache.pulsar.client.api.Message)72 Test (org.testng.annotations.Test)59 Producer (org.apache.pulsar.client.api.Producer)38 Consumer (org.apache.pulsar.client.api.Consumer)35 PulsarClientException (org.apache.pulsar.client.api.PulsarClientException)28 MessageId (org.apache.pulsar.client.api.MessageId)27 ProducerConfiguration (org.apache.pulsar.client.api.ProducerConfiguration)27 ConsumerConfiguration (org.apache.pulsar.client.api.ConsumerConfiguration)25 ExecutionException (java.util.concurrent.ExecutionException)20 IOException (java.io.IOException)19 CompletableFuture (java.util.concurrent.CompletableFuture)16 ExecutorService (java.util.concurrent.ExecutorService)15 MessageIdImpl (org.apache.pulsar.client.impl.MessageIdImpl)13 Map (java.util.Map)12 TimeUnit (java.util.concurrent.TimeUnit)12 List (java.util.List)11 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)11 PulsarClient (org.apache.pulsar.client.api.PulsarClient)10 Logger (org.slf4j.Logger)10 LoggerFactory (org.slf4j.LoggerFactory)10