Search in sources :

Example 1 with Reader

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

the class FunctionMetaDataManager method initialize.

/**
 * Public methods. Please use these methods if references FunctionMetaManager from an external class
 */
/**
 * Initializes the FunctionMetaDataManager.  Does the following:
 * 1. Restores from snapshot if one exists
 * 2. Sends out initialize marker to FMT and consume messages until the initialize marker is consumed
 */
public void initialize() {
    log.info("/** Initializing Function Metadata Manager **/");
    try {
        Reader reader = pulsarClient.newReader().topic(this.workerConfig.getFunctionMetadataTopic()).startMessageId(MessageId.earliest).create();
        this.functionMetaDataTopicTailer = new FunctionMetaDataTopicTailer(this, reader);
        // read all existing messages
        this.setInitializePhase(true);
        while (reader.hasMessageAvailable()) {
            this.functionMetaDataTopicTailer.processRequest(reader.readNext());
        }
        this.setInitializePhase(false);
        // schedule functions if necessary
        this.schedulerManager.schedule();
        // start function metadata tailer
        this.functionMetaDataTopicTailer.start();
    } catch (Exception e) {
        log.error("Failed to initialize meta data store: ", e.getMessage(), e);
        throw new RuntimeException(e);
    }
}
Also used : Reader(org.apache.pulsar.client.api.Reader) PulsarClientException(org.apache.pulsar.client.api.PulsarClientException)

Example 2 with Reader

use of org.apache.pulsar.client.api.Reader 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 3 with Reader

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

the class PerformanceReader method main.

public static void main(String[] args) throws Exception {
    final Arguments arguments = new Arguments();
    JCommander jc = new JCommander(arguments);
    jc.setProgramName("pulsar-perf-reader");
    try {
        jc.parse(args);
    } catch (ParameterException e) {
        System.out.println(e.getMessage());
        jc.usage();
        System.exit(-1);
    }
    if (arguments.help) {
        jc.usage();
        System.exit(-1);
    }
    if (arguments.topic.size() != 1) {
        System.out.println("Only one topic name is allowed");
        jc.usage();
        System.exit(-1);
    }
    if (arguments.confFile != null) {
        Properties prop = new Properties(System.getProperties());
        prop.load(new FileInputStream(arguments.confFile));
        if (arguments.serviceURL == null) {
            arguments.serviceURL = prop.getProperty("brokerServiceUrl");
        }
        if (arguments.serviceURL == null) {
            arguments.serviceURL = prop.getProperty("webServiceUrl");
        }
        // fallback to previous-version serviceUrl property to maintain backward-compatibility
        if (arguments.serviceURL == null) {
            arguments.serviceURL = prop.getProperty("serviceUrl", "http://localhost:8080/");
        }
        if (arguments.authPluginClassName == null) {
            arguments.authPluginClassName = prop.getProperty("authPlugin", null);
        }
        if (arguments.authParams == null) {
            arguments.authParams = prop.getProperty("authParams", null);
        }
        if (arguments.useTls == false) {
            arguments.useTls = Boolean.parseBoolean(prop.getProperty("useTls"));
        }
        if (isBlank(arguments.tlsTrustCertsFilePath)) {
            arguments.tlsTrustCertsFilePath = prop.getProperty("tlsTrustCertsFilePath", "");
        }
    }
    // Dump config variables
    ObjectMapper m = new ObjectMapper();
    ObjectWriter w = m.writerWithDefaultPrettyPrinter();
    log.info("Starting Pulsar performance reader with config: {}", w.writeValueAsString(arguments));
    final TopicName prefixTopicName = TopicName.get(arguments.topic.get(0));
    final RateLimiter limiter = arguments.rate > 0 ? RateLimiter.create(arguments.rate) : null;
    ReaderListener<byte[]> listener = (reader, msg) -> {
        messagesReceived.increment();
        bytesReceived.add(msg.getData().length);
        if (limiter != null) {
            limiter.acquire();
        }
    };
    ClientBuilder clientBuilder = // 
    PulsarClient.builder().serviceUrl(// 
    arguments.serviceURL).connectionsPerBroker(// 
    arguments.maxConnections).statsInterval(arguments.statsIntervalSeconds, // 
    TimeUnit.SECONDS).ioThreads(// 
    Runtime.getRuntime().availableProcessors()).enableTls(// 
    arguments.useTls).tlsTrustCertsFilePath(arguments.tlsTrustCertsFilePath);
    if (isNotBlank(arguments.authPluginClassName)) {
        clientBuilder.authentication(arguments.authPluginClassName, arguments.authParams);
    }
    PulsarClient pulsarClient = clientBuilder.build();
    List<CompletableFuture<Reader<byte[]>>> futures = Lists.newArrayList();
    MessageId startMessageId;
    if ("earliest".equals(arguments.startMessageId)) {
        startMessageId = MessageId.earliest;
    } else if ("latest".equals(arguments.startMessageId)) {
        startMessageId = MessageId.latest;
    } else {
        String[] parts = arguments.startMessageId.split(":");
        startMessageId = new MessageIdImpl(Long.parseLong(parts[0]), Long.parseLong(parts[1]), -1);
    }
    ReaderBuilder<byte[]> readerBuilder = // 
    pulsarClient.newReader().readerListener(// 
    listener).receiverQueueSize(// 
    arguments.receiverQueueSize).startMessageId(startMessageId);
    for (int i = 0; i < arguments.numTopics; i++) {
        final TopicName topicName = (arguments.numTopics == 1) ? prefixTopicName : TopicName.get(String.format("%s-%d", prefixTopicName, i));
        futures.add(readerBuilder.clone().topic(topicName.toString()).createAsync());
    }
    FutureUtil.waitForAll(futures).get();
    log.info("Start reading from {} topics", arguments.numTopics);
    long oldTime = System.nanoTime();
    while (true) {
        try {
            Thread.sleep(10000);
        } catch (InterruptedException e) {
            break;
        }
        long now = System.nanoTime();
        double elapsed = (now - oldTime) / 1e9;
        double rate = messagesReceived.sumThenReset() / elapsed;
        double throughput = bytesReceived.sumThenReset() / elapsed * 8 / 1024 / 1024;
        log.info("Read throughput: {}  msg/s -- {} Mbit/s", dec.format(rate), dec.format(throughput));
        oldTime = now;
    }
    pulsarClient.close();
}
Also used : LongAdder(java.util.concurrent.atomic.LongAdder) TopicName(org.apache.pulsar.common.naming.TopicName) ParameterException(com.beust.jcommander.ParameterException) Parameter(com.beust.jcommander.Parameter) LoggerFactory(org.slf4j.LoggerFactory) CompletableFuture(java.util.concurrent.CompletableFuture) RateLimiter(com.google.common.util.concurrent.RateLimiter) ReaderListener(org.apache.pulsar.client.api.ReaderListener) Lists(com.google.common.collect.Lists) PulsarClient(org.apache.pulsar.client.api.PulsarClient) Properties(java.util.Properties) Logger(org.slf4j.Logger) ObjectWriter(com.fasterxml.jackson.databind.ObjectWriter) DecimalFormat(java.text.DecimalFormat) JCommander(com.beust.jcommander.JCommander) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) Reader(org.apache.pulsar.client.api.Reader) FileInputStream(java.io.FileInputStream) TimeUnit(java.util.concurrent.TimeUnit) MessageIdImpl(org.apache.pulsar.client.impl.MessageIdImpl) List(java.util.List) FutureUtil(org.apache.pulsar.common.util.FutureUtil) StringUtils.isNotBlank(org.apache.commons.lang3.StringUtils.isNotBlank) MessageId(org.apache.pulsar.client.api.MessageId) StringUtils.isBlank(org.apache.commons.lang3.StringUtils.isBlank) ClientBuilder(org.apache.pulsar.client.api.ClientBuilder) ReaderBuilder(org.apache.pulsar.client.api.ReaderBuilder) ObjectWriter(com.fasterxml.jackson.databind.ObjectWriter) MessageIdImpl(org.apache.pulsar.client.impl.MessageIdImpl) Properties(java.util.Properties) FileInputStream(java.io.FileInputStream) RateLimiter(com.google.common.util.concurrent.RateLimiter) TopicName(org.apache.pulsar.common.naming.TopicName) CompletableFuture(java.util.concurrent.CompletableFuture) JCommander(com.beust.jcommander.JCommander) ParameterException(com.beust.jcommander.ParameterException) PulsarClient(org.apache.pulsar.client.api.PulsarClient) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) ClientBuilder(org.apache.pulsar.client.api.ClientBuilder) MessageId(org.apache.pulsar.client.api.MessageId)

Example 4 with Reader

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

the class TopicTerminationTest method testSimpleTerminationReaderListener.

@Test(timeOut = 20000)
public void testSimpleTerminationReaderListener() throws Exception {
    Producer<byte[]> producer = pulsarClient.newProducer().topic(topicName).create();
    CountDownLatch latch = new CountDownLatch(1);
    Reader<byte[]> reader = pulsarClient.newReader().topic(topicName).startMessageId(MessageId.latest).readerListener(new ReaderListener<byte[]>() {

        @Override
        public void received(Reader<byte[]> reader, Message<byte[]> msg) {
        // do nothing
        }

        @Override
        public void reachedEndOfTopic(Reader<byte[]> reader) {
            latch.countDown();
            assertTrue(reader.hasReachedEndOfTopic());
        }
    }).create();
    /* MessageId msgId1 = */
    producer.send("test-msg-1".getBytes());
    /* MessageId msgId2 = */
    producer.send("test-msg-2".getBytes());
    MessageId msgId3 = producer.send("test-msg-3".getBytes());
    Thread.sleep(100);
    assertFalse(reader.hasReachedEndOfTopic());
    MessageId lastMessageId = admin.persistentTopics().terminateTopicAsync(topicName).get();
    assertEquals(lastMessageId, msgId3);
    assertTrue(latch.await(3, TimeUnit.SECONDS));
    assertTrue(reader.hasReachedEndOfTopic());
}
Also used : Message(org.apache.pulsar.client.api.Message) Reader(org.apache.pulsar.client.api.Reader) CountDownLatch(java.util.concurrent.CountDownLatch) ReaderListener(org.apache.pulsar.client.api.ReaderListener) MessageId(org.apache.pulsar.client.api.MessageId) Test(org.testng.annotations.Test)

Aggregations

Reader (org.apache.pulsar.client.api.Reader)4 MessageId (org.apache.pulsar.client.api.MessageId)3 Message (org.apache.pulsar.client.api.Message)2 ReaderListener (org.apache.pulsar.client.api.ReaderListener)2 JCommander (com.beust.jcommander.JCommander)1 Parameter (com.beust.jcommander.Parameter)1 ParameterException (com.beust.jcommander.ParameterException)1 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)1 ObjectWriter (com.fasterxml.jackson.databind.ObjectWriter)1 Lists (com.google.common.collect.Lists)1 RateLimiter (com.google.common.util.concurrent.RateLimiter)1 FileInputStream (java.io.FileInputStream)1 IOException (java.io.IOException)1 DecimalFormat (java.text.DecimalFormat)1 List (java.util.List)1 Properties (java.util.Properties)1 CompletableFuture (java.util.concurrent.CompletableFuture)1 CountDownLatch (java.util.concurrent.CountDownLatch)1 ExecutionException (java.util.concurrent.ExecutionException)1 TimeUnit (java.util.concurrent.TimeUnit)1