Search in sources :

Example 1 with HistogramLogWriter

use of org.HdrHistogram.HistogramLogWriter in project pulsar by yahoo.

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.destinations.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);
        }
    }
    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.destinations.get(0);
    List<Future<Producer>> futures = Lists.newArrayList();
    EventLoopGroup eventLoopGroup;
    if (SystemUtils.IS_OS_LINUX) {
        eventLoopGroup = new EpollEventLoopGroup(Runtime.getRuntime().availableProcessors(), new DefaultThreadFactory("pulsar-perf-producer"));
    } else {
        eventLoopGroup = new NioEventLoopGroup(Runtime.getRuntime().availableProcessors(), new DefaultThreadFactory("pulsar-perf-producer"));
    }
    ClientConfiguration clientConf = new ClientConfiguration();
    clientConf.setConnectionsPerBroker(arguments.maxConnections);
    clientConf.setStatsInterval(arguments.statsIntervalSeconds, TimeUnit.SECONDS);
    if (isNotBlank(arguments.authPluginClassName)) {
        clientConf.setAuthentication(arguments.authPluginClassName, arguments.authParams);
    }
    PulsarClient client = new PulsarClientImpl(arguments.serviceURL, clientConf, eventLoopGroup);
    ProducerConfiguration producerConf = new ProducerConfiguration();
    producerConf.setSendTimeout(0, TimeUnit.SECONDS);
    producerConf.setCompressionType(arguments.compression);
    // enable round robin message routing if it is a partitioned topic
    producerConf.setMessageRoutingMode(MessageRoutingMode.RoundRobinPartition);
    if (arguments.batchTime > 0) {
        producerConf.setBatchingMaxPublishDelay(arguments.batchTime, TimeUnit.MILLISECONDS);
        producerConf.setBatchingEnabled(true);
        producerConf.setMaxPendingMessages(arguments.msgRate);
    }
    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 destination {}", arguments.numProducers, topic);
        for (int j = 0; j < arguments.numProducers; j++) {
            futures.add(client.createProducerAsync(topic, producerConf));
        }
    }
    final List<Producer> producers = Lists.newArrayListWithCapacity(futures.size());
    for (Future<Producer> 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 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) ProducerConfiguration(com.yahoo.pulsar.client.api.ProducerConfiguration) Properties(java.util.Properties) DefaultThreadFactory(io.netty.util.concurrent.DefaultThreadFactory) JCommander(com.beust.jcommander.JCommander) ParameterException(com.beust.jcommander.ParameterException) PulsarClient(com.yahoo.pulsar.client.api.PulsarClient) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) 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) EpollEventLoopGroup(io.netty.channel.epoll.EpollEventLoopGroup) EventLoopGroup(io.netty.channel.EventLoopGroup) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) Producer(com.yahoo.pulsar.client.api.Producer) EpollEventLoopGroup(io.netty.channel.epoll.EpollEventLoopGroup) FileOutputStream(java.io.FileOutputStream) Future(java.util.concurrent.Future) PulsarClientImpl(com.yahoo.pulsar.client.impl.PulsarClientImpl) ClientConfiguration(com.yahoo.pulsar.client.api.ClientConfiguration)

Example 2 with HistogramLogWriter

use of org.HdrHistogram.HistogramLogWriter in project LatencyUtils by LatencyUtils.

the class LatencyLoggingDemo method main.

public static void main(final String[] args) throws FileNotFoundException {
    // Knowing that we're using a SimplePauseDetector, set it to verbose so that the user can see
    // the pause detection messages:
    ((SimplePauseDetector) latencyStats.getPauseDetector()).setVerbose(true);
    final ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(2);
    // Record latencies on a "regular" basis. This will tend to record semi-reliably at
    // each interval as long as the JVM doesn't stall.
    executor.scheduleWithFixedDelay(new Recorder(), RECORDING_INTERVAL, RECORDING_INTERVAL, TimeUnit.NANOSECONDS);
    histogramLogWriter = new HistogramLogWriter(fillInPidAndDate(defaultLogFileName));
    histogramLogWriter.outputComment("[Logged with LatencyLoggingDemo]");
    histogramLogWriter.outputLogFormatVersion();
    reportingStartTime = System.currentTimeMillis();
    // Force an interval sample right at the reporting start time (to start samples here):
    latencyStats.getIntervalHistogram();
    histogramLogWriter.outputStartTime(reportingStartTime);
    histogramLogWriter.outputLegend();
    // Regularly report on observations into log file:
    executor.scheduleWithFixedDelay(new Reporter(), REPORTING_INTERVAL, REPORTING_INTERVAL, TimeUnit.NANOSECONDS);
    while (true) ;
}
Also used : HistogramLogWriter(org.HdrHistogram.HistogramLogWriter) ScheduledThreadPoolExecutor(java.util.concurrent.ScheduledThreadPoolExecutor) SimplePauseDetector(org.LatencyUtils.SimplePauseDetector)

Example 3 with HistogramLogWriter

use of org.HdrHistogram.HistogramLogWriter in project LatencyUtils by LatencyUtils.

the class LatencyComparativeLoggingDemo method main.

public static void main(final String[] args) throws FileNotFoundException {
    // Knowing that we're using a SimplePauseDetector, set it to verbose so that the user can see
    // the pause detection messages:
    ((SimplePauseDetector) latencyStats.getPauseDetector()).setVerbose(true);
    final ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(2);
    // Record latencies on a "regular" basis. This will tend to record semi-reliably at
    // each interval as long as the JVM doesn't stall.
    executor.scheduleWithFixedDelay(new Recorder(), RECORDING_INTERVAL, RECORDING_INTERVAL, TimeUnit.NANOSECONDS);
    histogramLogWriter = new HistogramLogWriter(fillInPidAndDate(defaultLogFileName));
    histogramLogWriter.outputComment("[Logged with LatencyLoggingDemo]");
    histogramLogWriter.outputLogFormatVersion();
    uncorrectedHistogramLogWriter = new HistogramLogWriter(fillInPidAndDate(defaultUncorrectedLogFileName));
    uncorrectedHistogramLogWriter.outputComment("[Logged with LatencyLoggingDemo (Raw)]");
    uncorrectedHistogramLogWriter.outputLogFormatVersion();
    reportingStartTime = System.currentTimeMillis();
    // Force an interval sample right at the reporting start time (to start samples here):
    latencyStats.getIntervalHistogram();
    histogramLogWriter.outputStartTime(reportingStartTime);
    histogramLogWriter.outputLegend();
    uncorrectedHistogramLogWriter.outputStartTime(reportingStartTime);
    uncorrectedHistogramLogWriter.outputLegend();
    // Regularly report on observations into log file:
    executor.scheduleWithFixedDelay(new Reporter(), REPORTING_INTERVAL, REPORTING_INTERVAL, TimeUnit.NANOSECONDS);
    while (true) ;
}
Also used : HistogramLogWriter(org.HdrHistogram.HistogramLogWriter) ScheduledThreadPoolExecutor(java.util.concurrent.ScheduledThreadPoolExecutor) SimplePauseDetector(org.LatencyUtils.SimplePauseDetector)

Example 4 with HistogramLogWriter

use of org.HdrHistogram.HistogramLogWriter in project pulsar by yahoo.

the class PerformanceClient method runPerformanceTest.

public void runPerformanceTest(long messages, long limit, int numOfTopic, int sizeOfMessage, String baseUrl, String destination) throws InterruptedException, FileNotFoundException {
    ExecutorService executor = Executors.newCachedThreadPool(new DefaultThreadFactory("pulsar-perf-producer-exec"));
    HashMap<String, Tuple> producersMap = new HashMap<>();
    String produceBaseEndPoint = baseUrl + destination;
    for (int i = 0; i < numOfTopic; i++) {
        String topic = produceBaseEndPoint + "1" + "/";
        URI produceUri = URI.create(topic);
        WebSocketClient produceClient = new WebSocketClient(new SslContextFactory(true));
        ClientUpgradeRequest produceRequest = new ClientUpgradeRequest();
        SimpleTestProducerSocket produceSocket = new SimpleTestProducerSocket();
        try {
            produceClient.start();
            produceClient.connect(produceSocket, produceUri, produceRequest);
        } catch (IOException e1) {
            log.error("Fail in connecting: [{}]", e1.getMessage());
            return;
        } catch (Exception e1) {
            log.error("Fail in starting client[{}]", e1.getMessage());
            return;
        }
        producersMap.put(produceUri.toString(), new Tuple(produceClient, produceRequest, produceSocket));
    }
    // connection to be established
    TimeUnit.SECONDS.sleep(5);
    executor.submit(() -> {
        try {
            RateLimiter rateLimiter = RateLimiter.create(limit);
            // Send messages on all topics/producers
            long totalSent = 0;
            while (true) {
                for (String topic : producersMap.keySet()) {
                    if (messages > 0) {
                        if (totalSent++ >= messages) {
                            log.trace("------------------- DONE -----------------------");
                            Thread.sleep(10000);
                            System.exit(0);
                        }
                    }
                    rateLimiter.acquire();
                    if (producersMap.get(topic).getSocket().getSession() == null) {
                        Thread.sleep(10000);
                        System.exit(0);
                    }
                    producersMap.get(topic).getSocket().sendMsg((String) String.valueOf(totalSent), sizeOfMessage);
                    messagesSent.increment();
                    bytesSent.add(1000);
                }
            }
        } catch (Throwable t) {
            log.error(t.getMessage());
            System.exit(0);
        }
    });
    // Print report stats
    long oldTime = System.nanoTime();
    Histogram reportHistogram = null;
    String statsFileName = "perf-websocket-producer-" + System.currentTimeMillis() + ".hgrm";
    log.info("Dumping latency stats to %s \n", 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(5000);
        } catch (InterruptedException e) {
            break;
        }
        long now = System.nanoTime();
        double elapsed = (now - oldTime) / 1e9;
        double rate = messagesSent.sumThenReset() / elapsed;
        double throughput = bytesSent.sumThenReset() / elapsed / 1024 / 1024 * 8;
        reportHistogram = SimpleTestProducerSocket.recorder.getIntervalHistogram(reportHistogram);
        log.info("Throughput produced: {}  msg/s --- {} Mbit/s --- Latency: mean: {} ms - med: {} ms - 95pct: {} ms - 99pct: {} ms - 99.9pct: {} ms - 99.99pct: {} ms", 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));
        histogramLogWriter.outputIntervalHistogram(reportHistogram);
        reportHistogram.reset();
        oldTime = now;
    }
    TimeUnit.SECONDS.sleep(100);
    executor.shutdown();
}
Also used : HistogramLogWriter(org.HdrHistogram.HistogramLogWriter) PrintStream(java.io.PrintStream) Histogram(org.HdrHistogram.Histogram) HashMap(java.util.HashMap) IOException(java.io.IOException) WebSocketClient(org.eclipse.jetty.websocket.client.WebSocketClient) URI(java.net.URI) ParameterException(com.beust.jcommander.ParameterException) IOException(java.io.IOException) FileNotFoundException(java.io.FileNotFoundException) RateLimiter(com.google.common.util.concurrent.RateLimiter) DefaultThreadFactory(io.netty.util.concurrent.DefaultThreadFactory) SslContextFactory(org.eclipse.jetty.util.ssl.SslContextFactory) FileOutputStream(java.io.FileOutputStream) ExecutorService(java.util.concurrent.ExecutorService) ClientUpgradeRequest(org.eclipse.jetty.websocket.client.ClientUpgradeRequest)

Aggregations

HistogramLogWriter (org.HdrHistogram.HistogramLogWriter)4 ParameterException (com.beust.jcommander.ParameterException)2 RateLimiter (com.google.common.util.concurrent.RateLimiter)2 DefaultThreadFactory (io.netty.util.concurrent.DefaultThreadFactory)2 FileOutputStream (java.io.FileOutputStream)2 PrintStream (java.io.PrintStream)2 ScheduledThreadPoolExecutor (java.util.concurrent.ScheduledThreadPoolExecutor)2 Histogram (org.HdrHistogram.Histogram)2 SimplePauseDetector (org.LatencyUtils.SimplePauseDetector)2 JCommander (com.beust.jcommander.JCommander)1 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)1 ObjectWriter (com.fasterxml.jackson.databind.ObjectWriter)1 ClientConfiguration (com.yahoo.pulsar.client.api.ClientConfiguration)1 Producer (com.yahoo.pulsar.client.api.Producer)1 ProducerConfiguration (com.yahoo.pulsar.client.api.ProducerConfiguration)1 PulsarClient (com.yahoo.pulsar.client.api.PulsarClient)1 PulsarClientImpl (com.yahoo.pulsar.client.impl.PulsarClientImpl)1 EventLoopGroup (io.netty.channel.EventLoopGroup)1 EpollEventLoopGroup (io.netty.channel.epoll.EpollEventLoopGroup)1 NioEventLoopGroup (io.netty.channel.nio.NioEventLoopGroup)1