Search in sources :

Example 1 with CryptoKeyReader

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

the class SampleCryptoProducer method main.

public static void main(String[] args) throws PulsarClientException, InterruptedException, IOException {
    class RawFileKeyReader implements CryptoKeyReader {

        String publicKeyFile = "";

        String privateKeyFile = "";

        RawFileKeyReader(String pubKeyFile, String privKeyFile) {
            publicKeyFile = pubKeyFile;
            privateKeyFile = privKeyFile;
        }

        @Override
        public EncryptionKeyInfo getPublicKey(String keyName, Map<String, String> keyMeta) {
            EncryptionKeyInfo keyInfo = new EncryptionKeyInfo();
            try {
                // Read the public key from the file
                keyInfo.setKey(Files.readAllBytes(Paths.get(publicKeyFile)));
            } catch (IOException e) {
                log.error("Failed to read public key from file {}", publicKeyFile, e);
            }
            return keyInfo;
        }

        @Override
        public EncryptionKeyInfo getPrivateKey(String keyName, Map<String, String> keyMeta) {
            EncryptionKeyInfo keyInfo = new EncryptionKeyInfo();
            try {
                // Read the private key from the file
                keyInfo.setKey(Files.readAllBytes(Paths.get(privateKeyFile)));
            } catch (IOException e) {
                log.error("Failed to read private key from file {}", privateKeyFile, e);
            }
            return keyInfo;
        }
    }
    PulsarClient pulsarClient = PulsarClient.builder().serviceUrl("http://127.0.0.1:8080").build();
    // Setup the CryptoKeyReader with the file name where public/private key is kept
    Producer<byte[]> producer = pulsarClient.newProducer().topic("persistent://my-property/use/my-ns/my-topic").cryptoKeyReader(new RawFileKeyReader("test_ecdsa_pubkey.pem", "test_ecdsa_privkey.pem")).addEncryptionKey("myappkey").create();
    for (int i = 0; i < 10; i++) {
        producer.send("my-message".getBytes());
    }
    pulsarClient.close();
}
Also used : EncryptionKeyInfo(org.apache.pulsar.client.api.EncryptionKeyInfo) IOException(java.io.IOException) PulsarClient(org.apache.pulsar.client.api.PulsarClient) Map(java.util.Map) CryptoKeyReader(org.apache.pulsar.client.api.CryptoKeyReader)

Example 2 with CryptoKeyReader

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

the class SampleCryptoConsumer method main.

public static void main(String[] args) throws PulsarClientException, InterruptedException {
    class RawFileKeyReader implements CryptoKeyReader {

        String publicKeyFile = "";

        String privateKeyFile = "";

        RawFileKeyReader(String pubKeyFile, String privKeyFile) {
            publicKeyFile = pubKeyFile;
            privateKeyFile = privKeyFile;
        }

        @Override
        public EncryptionKeyInfo getPublicKey(String keyName, Map<String, String> keyMeta) {
            // Read the public key from the file
            EncryptionKeyInfo keyInfo = new EncryptionKeyInfo();
            try {
                keyInfo.setKey(Files.readAllBytes(Paths.get(publicKeyFile)));
            } catch (IOException e) {
                log.error("Failed to read public key from file {}", publicKeyFile, e);
            }
            return keyInfo;
        }

        @Override
        public EncryptionKeyInfo getPrivateKey(String keyName, Map<String, String> keyMeta) {
            // Read the private key from the file
            EncryptionKeyInfo keyInfo = new EncryptionKeyInfo();
            try {
                keyInfo.setKey(Files.readAllBytes(Paths.get(privateKeyFile)));
            } catch (IOException e) {
                log.error("Failed to read private key from file {}", privateKeyFile, e);
            }
            return keyInfo;
        }
    }
    // Create pulsar client
    PulsarClient pulsarClient = PulsarClient.builder().serviceUrl("http://127.0.0.1:8080").build();
    Consumer<byte[]> consumer = pulsarClient.newConsumer().topic("persistent://my-property/use/my-ns/my-topic").subscriptionName("my-subscription-name").cryptoKeyReader(new RawFileKeyReader("test_ecdsa_pubkey.pem", "test_ecdsa_privkey.pem")).subscribe();
    Message<byte[]> msg = null;
    for (int i = 0; i < 10; i++) {
        msg = consumer.receive();
        // process the messsage
        log.info("Received: {}", new String(msg.getData()));
    }
    // Acknowledge the consumption of all messages at once
    consumer.acknowledgeCumulative(msg);
    pulsarClient.close();
}
Also used : EncryptionKeyInfo(org.apache.pulsar.client.api.EncryptionKeyInfo) IOException(java.io.IOException) PulsarClient(org.apache.pulsar.client.api.PulsarClient) Map(java.util.Map) CryptoKeyReader(org.apache.pulsar.client.api.CryptoKeyReader)

Example 3 with CryptoKeyReader

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

the class V1_ProducerConsumerTest method testEncryptionFailure.

@Test(groups = "encryption")
public void testEncryptionFailure() throws Exception {
    log.info("-- Starting {} test --", methodName);
    class EncKeyReader implements CryptoKeyReader {

        EncryptionKeyInfo keyInfo = new EncryptionKeyInfo();

        @Override
        public EncryptionKeyInfo getPublicKey(String keyName, Map<String, String> keyMeta) {
            String CERT_FILE_PATH = "./src/test/resources/certificate/public-key." + keyName;
            if (Files.isReadable(Paths.get(CERT_FILE_PATH))) {
                try {
                    keyInfo.setKey(Files.readAllBytes(Paths.get(CERT_FILE_PATH)));
                    return keyInfo;
                } catch (IOException e) {
                    log.error("Failed to read certificate from {}", CERT_FILE_PATH);
                }
            }
            return null;
        }

        @Override
        public EncryptionKeyInfo getPrivateKey(String keyName, Map<String, String> keyMeta) {
            String CERT_FILE_PATH = "./src/test/resources/certificate/private-key." + keyName;
            if (Files.isReadable(Paths.get(CERT_FILE_PATH))) {
                try {
                    keyInfo.setKey(Files.readAllBytes(Paths.get(CERT_FILE_PATH)));
                    return keyInfo;
                } catch (IOException e) {
                    log.error("Failed to read certificate from {}", CERT_FILE_PATH);
                }
            }
            return null;
        }
    }
    final int totalMsg = 10;
    ProducerConfiguration producerConf = new ProducerConfiguration();
    Message msg = null;
    Set<String> messageSet = Sets.newHashSet();
    ConsumerConfiguration conf = new ConsumerConfiguration();
    conf.setSubscriptionType(SubscriptionType.Exclusive);
    Consumer consumer = pulsarClient.subscribe("persistent://my-property/use/my-ns/myenc-topic1", "my-subscriber-name", conf);
    // 1. Invalid key name
    producerConf.addEncryptionKey("client-non-existant-rsa.pem");
    producerConf.setCryptoKeyReader(new EncKeyReader());
    try {
        pulsarClient.createProducer("persistent://my-property/use/myenc-ns/myenc-topic1", producerConf);
        Assert.fail("Producer creation should not suceed if failing to read key");
    } catch (Exception e) {
    // ok
    }
    // 2. Producer with valid key name
    producerConf = new ProducerConfiguration();
    producerConf.setCryptoKeyReader(new EncKeyReader());
    producerConf.addEncryptionKey("client-rsa.pem");
    Producer producer = pulsarClient.createProducer("persistent://my-property/use/my-ns/myenc-topic1", producerConf);
    for (int i = 0; i < totalMsg; i++) {
        String message = "my-message-" + i;
        producer.send(message.getBytes());
    }
    // 3. KeyReder is not set by consumer
    // Receive should fail since key reader is not setup
    msg = consumer.receive(5, TimeUnit.SECONDS);
    Assert.assertNull(msg, "Receive should have failed with no keyreader");
    // 4. Set consumer config to consume even if decryption fails
    conf.setCryptoFailureAction(ConsumerCryptoFailureAction.CONSUME);
    consumer.close();
    consumer = pulsarClient.subscribe("persistent://my-property/use/my-ns/myenc-topic1", "my-subscriber-name", conf);
    int msgNum = 0;
    try {
        // Receive should proceed and deliver encrypted message
        msg = consumer.receive(5, TimeUnit.SECONDS);
        String receivedMessage = new String(msg.getData());
        String expectedMessage = "my-message-" + msgNum++;
        Assert.assertNotEquals(receivedMessage, expectedMessage, "Received encrypted message " + receivedMessage + " should not match the expected message " + expectedMessage);
        consumer.acknowledgeCumulative(msg);
    } catch (Exception e) {
        Assert.fail("Failed to receive message even aftet ConsumerCryptoFailureAction.CONSUME is set.");
    }
    // 5. Set keyreader and failure action
    conf.setCryptoFailureAction(ConsumerCryptoFailureAction.FAIL);
    consumer.close();
    // Set keyreader
    conf.setCryptoKeyReader(new EncKeyReader());
    consumer = pulsarClient.subscribe("persistent://my-property/use/my-ns/myenc-topic1", "my-subscriber-name", conf);
    for (int i = msgNum; i < totalMsg - 1; i++) {
        msg = consumer.receive(5, TimeUnit.SECONDS);
        String receivedMessage = new String(msg.getData());
        log.debug("Received message: [{}]", receivedMessage);
        String expectedMessage = "my-message-" + i;
        testMessageOrderAndDuplicates(messageSet, receivedMessage, expectedMessage);
    }
    // Acknowledge the consumption of all messages at once
    consumer.acknowledgeCumulative(msg);
    consumer.close();
    // 6. Set consumer config to discard if decryption fails
    consumer.close();
    ConsumerConfiguration conf2 = new ConsumerConfiguration();
    conf2.setSubscriptionType(SubscriptionType.Exclusive);
    conf2.setCryptoFailureAction(ConsumerCryptoFailureAction.DISCARD);
    consumer = pulsarClient.subscribe("persistent://my-property/use/my-ns/myenc-topic1", "my-subscriber-name", conf2);
    // Receive should proceed and discard encrypted messages
    msg = consumer.receive(5, TimeUnit.SECONDS);
    Assert.assertNull(msg, "Message received even aftet ConsumerCryptoFailureAction.DISCARD is set.");
    log.info("-- Exiting {} test --", methodName);
}
Also used : Message(org.apache.pulsar.client.api.Message) ProducerConfiguration(org.apache.pulsar.client.api.ProducerConfiguration) EncryptionKeyInfo(org.apache.pulsar.client.api.EncryptionKeyInfo) IOException(java.io.IOException) CryptoKeyReader(org.apache.pulsar.client.api.CryptoKeyReader) PulsarClientException(org.apache.pulsar.client.api.PulsarClientException) IOException(java.io.IOException) ExecutionException(java.util.concurrent.ExecutionException) Consumer(org.apache.pulsar.client.api.Consumer) Producer(org.apache.pulsar.client.api.Producer) ConsumerConfiguration(org.apache.pulsar.client.api.ConsumerConfiguration) Map(java.util.Map) Test(org.testng.annotations.Test)

Example 4 with CryptoKeyReader

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

the class PerformanceConsumer method main.

public static void main(String[] args) throws Exception {
    final Arguments arguments = new Arguments();
    JCommander jc = new JCommander(arguments);
    jc.setProgramName("pulsar-perf-consumer");
    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 consumer 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;
    MessageListener<byte[]> listener = (consumer, msg) -> {
        messagesReceived.increment();
        bytesReceived.add(msg.getData().length);
        if (limiter != null) {
            limiter.acquire();
        }
        long latencyMillis = System.currentTimeMillis() - msg.getPublishTime();
        if (latencyMillis >= 0) {
            recorder.recordValue(latencyMillis);
            cumulativeRecorder.recordValue(latencyMillis);
        }
        consumer.acknowledgeAsync(msg);
    };
    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();
    class EncKeyReader implements CryptoKeyReader {

        EncryptionKeyInfo keyInfo = new EncryptionKeyInfo();

        EncKeyReader(byte[] value) {
            keyInfo.setKey(value);
        }

        @Override
        public EncryptionKeyInfo getPublicKey(String keyName, Map<String, String> keyMeta) {
            return null;
        }

        @Override
        public EncryptionKeyInfo getPrivateKey(String keyName, Map<String, String> keyMeta) {
            if (keyName.equals(arguments.encKeyName)) {
                return keyInfo;
            }
            return null;
        }
    }
    List<Future<Consumer<byte[]>>> futures = Lists.newArrayList();
    ConsumerBuilder<byte[]> consumerBuilder = // 
    pulsarClient.newConsumer().messageListener(// 
    listener).receiverQueueSize(// 
    arguments.receiverQueueSize).subscriptionType(arguments.subscriptionType);
    if (arguments.encKeyName != null) {
        byte[] pKey = Files.readAllBytes(Paths.get(arguments.encKeyFile));
        EncKeyReader keyReader = new EncKeyReader(pKey);
        consumerBuilder.cryptoKeyReader(keyReader);
    }
    for (int i = 0; i < arguments.numTopics; i++) {
        final TopicName topicName = (arguments.numTopics == 1) ? prefixTopicName : TopicName.get(String.format("%s-%d", prefixTopicName, i));
        log.info("Adding {} consumers on topic {}", arguments.numConsumers, topicName);
        for (int j = 0; j < arguments.numConsumers; j++) {
            String subscriberName;
            if (arguments.numConsumers > 1) {
                subscriberName = String.format("%s-%d", arguments.subscriberName, j);
            } else {
                subscriberName = arguments.subscriberName;
            }
            futures.add(consumerBuilder.clone().topic(topicName.toString()).subscriptionName(subscriberName).subscribeAsync());
        }
    }
    for (Future<Consumer<byte[]>> future : futures) {
        future.get();
    }
    log.info("Start receiving from {} consumers on {} topics", arguments.numConsumers, arguments.numTopics);
    Runtime.getRuntime().addShutdownHook(new Thread() {

        public void run() {
            printAggregatedStats();
        }
    });
    long oldTime = System.nanoTime();
    Histogram reportHistogram = null;
    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;
        reportHistogram = recorder.getIntervalHistogram(reportHistogram);
        log.info("Throughput received: {}  msg/s -- {} Mbit/s --- Latency: mean: {} ms - med: {} - 95pct: {} - 99pct: {} - 99.9pct: {} - 99.99pct: {} - Max: {}", dec.format(rate), dec.format(throughput), dec.format(reportHistogram.getMean()), (long) reportHistogram.getValueAtPercentile(50), (long) reportHistogram.getValueAtPercentile(95), (long) reportHistogram.getValueAtPercentile(99), (long) reportHistogram.getValueAtPercentile(99.9), (long) reportHistogram.getValueAtPercentile(99.99), (long) reportHistogram.getMaxValue());
        reportHistogram.reset();
        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) ConsumerBuilder(org.apache.pulsar.client.api.ConsumerBuilder) RateLimiter(com.google.common.util.concurrent.RateLimiter) Future(java.util.concurrent.Future) Lists(com.google.common.collect.Lists) Map(java.util.Map) Recorder(org.HdrHistogram.Recorder) EncryptionKeyInfo(org.apache.pulsar.client.api.EncryptionKeyInfo) PulsarClient(org.apache.pulsar.client.api.PulsarClient) Properties(java.util.Properties) Logger(org.slf4j.Logger) Files(java.nio.file.Files) ObjectWriter(com.fasterxml.jackson.databind.ObjectWriter) MessageListener(org.apache.pulsar.client.api.MessageListener) DecimalFormat(java.text.DecimalFormat) JCommander(com.beust.jcommander.JCommander) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) FileInputStream(java.io.FileInputStream) SubscriptionType(org.apache.pulsar.client.api.SubscriptionType) TimeUnit(java.util.concurrent.TimeUnit) Histogram(org.HdrHistogram.Histogram) Consumer(org.apache.pulsar.client.api.Consumer) CryptoKeyReader(org.apache.pulsar.client.api.CryptoKeyReader) List(java.util.List) StringUtils.isNotBlank(org.apache.commons.lang3.StringUtils.isNotBlank) StringUtils.isBlank(org.apache.commons.lang3.StringUtils.isBlank) Paths(java.nio.file.Paths) ClientBuilder(org.apache.pulsar.client.api.ClientBuilder) Histogram(org.HdrHistogram.Histogram) EncryptionKeyInfo(org.apache.pulsar.client.api.EncryptionKeyInfo) Properties(java.util.Properties) CryptoKeyReader(org.apache.pulsar.client.api.CryptoKeyReader) Consumer(org.apache.pulsar.client.api.Consumer) 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) ObjectWriter(com.fasterxml.jackson.databind.ObjectWriter) FileInputStream(java.io.FileInputStream) RateLimiter(com.google.common.util.concurrent.RateLimiter) TopicName(org.apache.pulsar.common.naming.TopicName) Future(java.util.concurrent.Future) Map(java.util.Map)

Example 5 with CryptoKeyReader

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

the class PerformanceProducer method main.

public static void main(String[] args) throws Exception {
    final Arguments arguments = new Arguments();
    JCommander jc = new JCommander(arguments);
    jc.setProgramName("pulsar-perf-producer");
    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.topics.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", "");
        }
    }
    arguments.testTime = TimeUnit.SECONDS.toMillis(arguments.testTime);
    // Dump config variables
    ObjectMapper m = new ObjectMapper();
    ObjectWriter w = m.writerWithDefaultPrettyPrinter();
    log.info("Starting Pulsar perf producer with config: {}", w.writeValueAsString(arguments));
    // Read payload data from file if needed
    byte[] payloadData;
    if (arguments.payloadFilename != null) {
        payloadData = Files.readAllBytes(Paths.get(arguments.payloadFilename));
    } else {
        payloadData = new byte[arguments.msgSize];
    }
    // Now processing command line arguments
    String prefixTopicName = arguments.topics.get(0);
    List<Future<Producer<byte[]>>> futures = Lists.newArrayList();
    ClientBuilder clientBuilder = // 
    PulsarClient.builder().serviceUrl(// 
    arguments.serviceURL).connectionsPerBroker(// 
    arguments.maxConnections).ioThreads(// 
    Runtime.getRuntime().availableProcessors()).statsInterval(arguments.statsIntervalSeconds, // 
    TimeUnit.SECONDS).enableTls(// 
    arguments.useTls).tlsTrustCertsFilePath(arguments.tlsTrustCertsFilePath);
    if (isNotBlank(arguments.authPluginClassName)) {
        clientBuilder.authentication(arguments.authPluginClassName, arguments.authParams);
    }
    class EncKeyReader implements CryptoKeyReader {

        EncryptionKeyInfo keyInfo = new EncryptionKeyInfo();

        EncKeyReader(byte[] value) {
            keyInfo.setKey(value);
        }

        @Override
        public EncryptionKeyInfo getPublicKey(String keyName, Map<String, String> keyMeta) {
            if (keyName.equals(arguments.encKeyName)) {
                return keyInfo;
            }
            return null;
        }

        @Override
        public EncryptionKeyInfo getPrivateKey(String keyName, Map<String, String> keyMeta) {
            return null;
        }
    }
    PulsarClient client = clientBuilder.build();
    ProducerBuilder<byte[]> producerBuilder = // 
    client.newProducer().sendTimeout(0, // 
    TimeUnit.SECONDS).compressionType(// 
    arguments.compression).maxPendingMessages(// 
    arguments.maxOutstanding).messageRoutingMode(MessageRoutingMode.RoundRobinPartition);
    if (arguments.batchTime > 0) {
        producerBuilder.batchingMaxPublishDelay(arguments.batchTime, TimeUnit.MILLISECONDS).enableBatching(true);
    }
    // Block if queue is full else we will start seeing errors in sendAsync
    producerBuilder.blockIfQueueFull(true);
    if (arguments.encKeyName != null) {
        producerBuilder.addEncryptionKey(arguments.encKeyName);
        byte[] pKey = Files.readAllBytes(Paths.get(arguments.encKeyFile));
        EncKeyReader keyReader = new EncKeyReader(pKey);
        producerBuilder.cryptoKeyReader(keyReader);
    }
    for (int i = 0; i < arguments.numTopics; i++) {
        String topic = (arguments.numTopics == 1) ? prefixTopicName : String.format("%s-%d", prefixTopicName, i);
        log.info("Adding {} publishers on topic {}", arguments.numProducers, topic);
        for (int j = 0; j < arguments.numProducers; j++) {
            futures.add(producerBuilder.clone().topic(topic).createAsync());
        }
    }
    final List<Producer<byte[]>> producers = Lists.newArrayListWithCapacity(futures.size());
    for (Future<Producer<byte[]>> future : futures) {
        producers.add(future.get());
    }
    log.info("Created {} producers", producers.size());
    Runtime.getRuntime().addShutdownHook(new Thread() {

        public void run() {
            printAggregatedStats();
        }
    });
    Collections.shuffle(producers);
    AtomicBoolean isDone = new AtomicBoolean();
    executor.submit(() -> {
        try {
            RateLimiter rateLimiter = RateLimiter.create(arguments.msgRate);
            long startTime = System.currentTimeMillis();
            // Send messages on all topics/producers
            long totalSent = 0;
            while (true) {
                for (Producer<byte[]> producer : producers) {
                    if (arguments.testTime > 0) {
                        if (System.currentTimeMillis() - startTime > arguments.testTime) {
                            log.info("------------------- DONE -----------------------");
                            printAggregatedStats();
                            isDone.set(true);
                            Thread.sleep(5000);
                            System.exit(0);
                        }
                    }
                    if (arguments.numMessages > 0) {
                        if (totalSent++ >= arguments.numMessages) {
                            log.info("------------------- DONE -----------------------");
                            printAggregatedStats();
                            isDone.set(true);
                            Thread.sleep(5000);
                            System.exit(0);
                        }
                    }
                    rateLimiter.acquire();
                    final long sendTime = System.nanoTime();
                    producer.sendAsync(payloadData).thenRun(() -> {
                        messagesSent.increment();
                        bytesSent.add(payloadData.length);
                        long latencyMicros = NANOSECONDS.toMicros(System.nanoTime() - sendTime);
                        recorder.recordValue(latencyMicros);
                        cumulativeRecorder.recordValue(latencyMicros);
                    }).exceptionally(ex -> {
                        log.warn("Write error on message", ex);
                        System.exit(-1);
                        return null;
                    });
                }
            }
        } catch (Throwable t) {
            log.error("Got error", t);
        }
    });
    // Print report stats
    long oldTime = System.nanoTime();
    Histogram reportHistogram = null;
    String statsFileName = "perf-producer-" + System.currentTimeMillis() + ".hgrm";
    log.info("Dumping latency stats to {}", statsFileName);
    PrintStream histogramLog = new PrintStream(new FileOutputStream(statsFileName), false);
    HistogramLogWriter histogramLogWriter = new HistogramLogWriter(histogramLog);
    // Some log header bits
    histogramLogWriter.outputLogFormatVersion();
    histogramLogWriter.outputLegend();
    while (true) {
        try {
            Thread.sleep(10000);
        } catch (InterruptedException e) {
            break;
        }
        if (isDone.get()) {
            break;
        }
        long now = System.nanoTime();
        double elapsed = (now - oldTime) / 1e9;
        double rate = messagesSent.sumThenReset() / elapsed;
        double throughput = bytesSent.sumThenReset() / elapsed / 1024 / 1024 * 8;
        reportHistogram = recorder.getIntervalHistogram(reportHistogram);
        log.info("Throughput produced: {}  msg/s --- {} Mbit/s --- Latency: mean: {} ms - med: {} - 95pct: {} - 99pct: {} - 99.9pct: {} - 99.99pct: {} - Max: {}", throughputFormat.format(rate), throughputFormat.format(throughput), dec.format(reportHistogram.getMean() / 1000.0), dec.format(reportHistogram.getValueAtPercentile(50) / 1000.0), dec.format(reportHistogram.getValueAtPercentile(95) / 1000.0), dec.format(reportHistogram.getValueAtPercentile(99) / 1000.0), dec.format(reportHistogram.getValueAtPercentile(99.9) / 1000.0), dec.format(reportHistogram.getValueAtPercentile(99.99) / 1000.0), dec.format(reportHistogram.getMaxValue() / 1000.0));
        histogramLogWriter.outputIntervalHistogram(reportHistogram);
        reportHistogram.reset();
        oldTime = now;
    }
    client.close();
}
Also used : Histogram(org.HdrHistogram.Histogram) EncryptionKeyInfo(org.apache.pulsar.client.api.EncryptionKeyInfo) Properties(java.util.Properties) CryptoKeyReader(org.apache.pulsar.client.api.CryptoKeyReader) 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) HistogramLogWriter(org.HdrHistogram.HistogramLogWriter) PrintStream(java.io.PrintStream) ObjectWriter(com.fasterxml.jackson.databind.ObjectWriter) FileInputStream(java.io.FileInputStream) RateLimiter(com.google.common.util.concurrent.RateLimiter) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Producer(org.apache.pulsar.client.api.Producer) FileOutputStream(java.io.FileOutputStream) Future(java.util.concurrent.Future) Map(java.util.Map)

Aggregations

Map (java.util.Map)7 CryptoKeyReader (org.apache.pulsar.client.api.CryptoKeyReader)7 EncryptionKeyInfo (org.apache.pulsar.client.api.EncryptionKeyInfo)7 IOException (java.io.IOException)5 Consumer (org.apache.pulsar.client.api.Consumer)4 Producer (org.apache.pulsar.client.api.Producer)4 PulsarClient (org.apache.pulsar.client.api.PulsarClient)4 ConsumerConfiguration (org.apache.pulsar.client.api.ConsumerConfiguration)3 Message (org.apache.pulsar.client.api.Message)3 ProducerConfiguration (org.apache.pulsar.client.api.ProducerConfiguration)3 Test (org.testng.annotations.Test)3 JCommander (com.beust.jcommander.JCommander)2 ParameterException (com.beust.jcommander.ParameterException)2 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)2 ObjectWriter (com.fasterxml.jackson.databind.ObjectWriter)2 RateLimiter (com.google.common.util.concurrent.RateLimiter)2 FileInputStream (java.io.FileInputStream)2 Properties (java.util.Properties)2 Future (java.util.concurrent.Future)2 Histogram (org.HdrHistogram.Histogram)2