Search in sources :

Example 1 with MessageIdImpl

use of org.apache.pulsar.client.impl.MessageIdImpl in project incubator-pulsar by apache.

the class PersistentTopicsImpl method terminateTopicAsync.

@Override
public CompletableFuture<MessageId> terminateTopicAsync(String topic) {
    TopicName tn = validateTopic(topic);
    final CompletableFuture<MessageId> future = new CompletableFuture<>();
    try {
        final WebTarget path = topicPath(tn, "terminate");
        request(path).async().post(Entity.entity("", MediaType.APPLICATION_JSON), new InvocationCallback<MessageIdImpl>() {

            @Override
            public void completed(MessageIdImpl messageId) {
                future.complete(messageId);
            }

            @Override
            public void failed(Throwable throwable) {
                log.warn("[{}] Failed to perform http post request: {}", path.getUri(), throwable.getMessage());
                future.completeExceptionally(getApiException(throwable.getCause()));
            }
        });
    } catch (PulsarAdminException cae) {
        future.completeExceptionally(cae);
    }
    return future;
}
Also used : CompletableFuture(java.util.concurrent.CompletableFuture) MessageIdImpl(org.apache.pulsar.client.impl.MessageIdImpl) WebTarget(javax.ws.rs.client.WebTarget) PulsarAdminException(org.apache.pulsar.client.admin.PulsarAdminException) TopicName(org.apache.pulsar.common.naming.TopicName) MessageId(org.apache.pulsar.client.api.MessageId)

Example 2 with MessageIdImpl

use of org.apache.pulsar.client.impl.MessageIdImpl in project incubator-pulsar by apache.

the class PulsarKafkaProducer method getRecordMetadata.

private RecordMetadata getRecordMetadata(String topic, Message<byte[]> msg, MessageId messageId, int size) {
    MessageIdImpl msgId = (MessageIdImpl) messageId;
    // Combine ledger id and entry id to form offset
    long offset = MessageIdUtils.getOffset(msgId);
    int partition = msgId.getPartitionIndex();
    TopicPartition tp = new TopicPartition(topic, partition);
    return new RecordMetadata(tp, offset, 0, msg.getPublishTime(), 0, msg.hasKey() ? msg.getKey().length() : 0, size);
}
Also used : TopicPartition(org.apache.kafka.common.TopicPartition) MessageIdImpl(org.apache.pulsar.client.impl.MessageIdImpl)

Example 3 with MessageIdImpl

use of org.apache.pulsar.client.impl.MessageIdImpl in project incubator-pulsar by apache.

the class Utils method getSequenceId.

public static final long getSequenceId(MessageId messageId) {
    MessageIdImpl msgId = (MessageIdImpl) messageId;
    long ledgerId = msgId.getLedgerId();
    long entryId = msgId.getEntryId();
    // Combine ledger id and entry id to form offset
    // Use less than 32 bits to represent entry id since it will get
    // rolled over way before overflowing the max int range
    long offset = (ledgerId << 28) | entryId;
    return offset;
}
Also used : MessageIdImpl(org.apache.pulsar.client.impl.MessageIdImpl)

Example 4 with MessageIdImpl

use of org.apache.pulsar.client.impl.MessageIdImpl in project incubator-pulsar by apache.

the class MessageIdTest method messageIdTest.

@Test
public void messageIdTest() {
    MessageId mId = new MessageIdImpl(1, 2, 3);
    assertEquals(mId.toString(), "1:2:3");
    mId = new BatchMessageIdImpl(0, 2, 3, 4);
    assertEquals(mId.toString(), "0:2:3:4");
    mId = new BatchMessageIdImpl(-1, 2, -3, 4);
    assertEquals(mId.toString(), "-1:2:-3:4");
    mId = new MessageIdImpl(0, -23, 3);
    assertEquals(mId.toString(), "0:-23:3");
}
Also used : MessageIdImpl(org.apache.pulsar.client.impl.MessageIdImpl) BatchMessageIdImpl(org.apache.pulsar.client.impl.BatchMessageIdImpl) BatchMessageIdImpl(org.apache.pulsar.client.impl.BatchMessageIdImpl) Test(org.testng.annotations.Test)

Example 5 with MessageIdImpl

use of org.apache.pulsar.client.impl.MessageIdImpl 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)

Aggregations

MessageIdImpl (org.apache.pulsar.client.impl.MessageIdImpl)29 Test (org.testng.annotations.Test)18 MessageId (org.apache.pulsar.client.api.MessageId)15 Message (org.apache.pulsar.client.api.Message)11 CompletableFuture (java.util.concurrent.CompletableFuture)9 ExecutorService (java.util.concurrent.ExecutorService)9 TopicName (org.apache.pulsar.common.naming.TopicName)8 List (java.util.List)6 TimeUnit (java.util.concurrent.TimeUnit)6 Cleanup (lombok.Cleanup)6 FunctionConfig (org.apache.pulsar.functions.proto.Function.FunctionConfig)6 Matchers.anyString (org.mockito.Matchers.anyString)6 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)6 Map (java.util.Map)5 Set (java.util.Set)5 PersistentTopic (org.apache.pulsar.broker.service.persistent.PersistentTopic)5 Lists (com.google.common.collect.Lists)4 Collectors (java.util.stream.Collectors)4 ManagedLedgerImpl (org.apache.bookkeeper.mledger.impl.ManagedLedgerImpl)4 FutureUtil (org.apache.pulsar.common.util.FutureUtil)4