Search in sources :

Example 11 with ObjectWriter

use of com.fasterxml.jackson.databind.ObjectWriter in project torodb by torodb.

the class ConfigUtils method printYamlConfig.

public static <T> void printYamlConfig(T config, Console console) throws IOException, JsonGenerationException, JsonMappingException {
    ObjectMapper objectMapper = yamlMapper();
    ObjectWriter objectWriter = objectMapper.writer();
    printConfig(config, console, objectWriter);
}
Also used : ObjectWriter(com.fasterxml.jackson.databind.ObjectWriter) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper)

Example 12 with ObjectWriter

use of com.fasterxml.jackson.databind.ObjectWriter in project pulsar by yahoo.

the class ConsumerStats method init.

private void init(ConsumerConfiguration conf) {
    ObjectMapper m = new ObjectMapper();
    m.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
    ObjectWriter w = m.writerWithDefaultPrettyPrinter();
    try {
        log.info("Starting Pulsar consumer perf with config: {}", w.writeValueAsString(conf));
        log.info("Pulsar client config: {}", w.writeValueAsString(pulsarClient.getConfiguration()));
    } catch (IOException e) {
        log.error("Failed to dump config info: {}", e);
    }
    stat = (timeout) -> {
        if (timeout.isCancelled()) {
            return;
        }
        try {
            long now = System.nanoTime();
            double elapsed = (now - oldTime) / 1e9;
            oldTime = now;
            long currentNumMsgsReceived = numMsgsReceived.sumThenReset();
            long currentNumBytesReceived = numBytesReceived.sumThenReset();
            long currentNumReceiveFailed = numReceiveFailed.sumThenReset();
            long currentNumAcksSent = numAcksSent.sumThenReset();
            long currentNumAcksFailed = numAcksFailed.sumThenReset();
            totalMsgsReceived.add(currentNumMsgsReceived);
            totalBytesReceived.add(currentNumBytesReceived);
            totalReceiveFailed.add(currentNumReceiveFailed);
            totalAcksSent.add(currentNumAcksSent);
            totalAcksFailed.add(currentNumAcksFailed);
            if ((currentNumMsgsReceived | currentNumBytesReceived | currentNumReceiveFailed | currentNumAcksSent | currentNumAcksFailed) != 0) {
                log.info("[{}] [{}] [{}] Prefetched messages: {} --- Consume throughput: {} msgs/s --- " + "Throughput received: {} msg/s --- {} Mbit/s --- " + "Ack sent rate: {} ack/s --- " + "Failed messages: {} --- " + "Failed acks: {}", consumer.getTopic(), consumer.getSubscription(), consumer.consumerName, consumer.incomingMessages.size(), throughputFormat.format(currentNumMsgsReceived / elapsed), throughputFormat.format(currentNumBytesReceived / elapsed * 8 / 1024 / 1024), throughputFormat.format(currentNumAcksSent / elapsed), currentNumReceiveFailed, currentNumAcksFailed);
            }
        } catch (Exception e) {
            log.error("[{}] [{}] [{}]: {}", consumer.getTopic(), consumer.subscription, consumer.consumerName, e.getMessage());
        } finally {
            // schedule the next stat info
            statTimeout = pulsarClient.timer().newTimeout(stat, statsIntervalSeconds, TimeUnit.SECONDS);
        }
    };
    oldTime = System.nanoTime();
    statTimeout = pulsarClient.timer().newTimeout(stat, statsIntervalSeconds, TimeUnit.SECONDS);
}
Also used : ObjectWriter(com.fasterxml.jackson.databind.ObjectWriter) IOException(java.io.IOException) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) IOException(java.io.IOException)

Example 13 with ObjectWriter

use of com.fasterxml.jackson.databind.ObjectWriter in project pulsar by yahoo.

the class ProducerStats method init.

private void init(ProducerConfiguration conf) {
    ObjectMapper m = new ObjectMapper();
    m.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
    ObjectWriter w = m.writerWithDefaultPrettyPrinter();
    try {
        log.info("Starting Pulsar producer perf with config: {}", w.writeValueAsString(conf));
        log.info("Pulsar client config: {}", w.writeValueAsString(pulsarClient.getConfiguration()));
    } catch (IOException e) {
        log.error("Failed to dump config info: {}", e);
    }
    stat = (timeout) -> {
        if (timeout.isCancelled()) {
            return;
        }
        try {
            long now = System.nanoTime();
            double elapsed = (now - oldTime) / 1e9;
            oldTime = now;
            long currentNumMsgsSent = numMsgsSent.sumThenReset();
            long currentNumBytesSent = numBytesSent.sumThenReset();
            long currentNumSendFailedMsgs = numSendFailed.sumThenReset();
            long currentNumAcksReceived = numAcksReceived.sumThenReset();
            totalMsgsSent.add(currentNumMsgsSent);
            totalBytesSent.add(currentNumBytesSent);
            totalSendFailed.add(currentNumSendFailedMsgs);
            totalAcksReceived.add(currentNumAcksReceived);
            double[] percentileValues;
            synchronized (ds) {
                percentileValues = ds.getQuantiles(percentiles);
                ds.reset();
            }
            if ((currentNumMsgsSent | currentNumSendFailedMsgs | currentNumAcksReceived | currentNumMsgsSent) != 0) {
                for (int i = 0; i < percentileValues.length; i++) {
                    if (percentileValues[i] == Double.NaN) {
                        percentileValues[i] = 0;
                    }
                }
                log.info("[{}] [{}] Pending messages: {} --- Publish throughput: {} msg/s --- {} Mbit/s --- " + "Latency: med: {} ms - 95pct: {} ms - 99pct: {} ms - 99.9pct: {} ms - 99.99pct: {} ms --- " + "Ack received rate: {} ack/s --- Failed messages: {}", producer.getTopic(), producer.getProducerName(), producer.getPendingQueueSize(), throughputFormat.format(currentNumMsgsSent / elapsed), throughputFormat.format(currentNumBytesSent / elapsed / 1024 / 1024 * 8), dec.format(percentileValues[0] / 1000.0), dec.format(percentileValues[1] / 1000.0), dec.format(percentileValues[2] / 1000.0), dec.format(percentileValues[3] / 1000.0), dec.format(percentileValues[4] / 1000.0), throughputFormat.format(currentNumAcksReceived / elapsed), currentNumSendFailedMsgs);
            }
        } catch (Exception e) {
            log.error("[{}] [{}]: {}", producer.getTopic(), producer.getProducerName(), e.getMessage());
        } finally {
            // schedule the next stat info
            statTimeout = pulsarClient.timer().newTimeout(stat, statsIntervalSeconds, TimeUnit.SECONDS);
        }
    };
    oldTime = System.nanoTime();
    statTimeout = pulsarClient.timer().newTimeout(stat, statsIntervalSeconds, TimeUnit.SECONDS);
}
Also used : ObjectWriter(com.fasterxml.jackson.databind.ObjectWriter) IOException(java.io.IOException) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) IOException(java.io.IOException)

Example 14 with ObjectWriter

use of com.fasterxml.jackson.databind.ObjectWriter 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 15 with ObjectWriter

use of com.fasterxml.jackson.databind.ObjectWriter in project jackson-databind by FasterXML.

the class TestJDKSerialization method testObjectWriter.

public void testObjectWriter() throws IOException {
    ObjectWriter origWriter = MAPPER.writer();
    final String EXP_JSON = "{\"x\":2,\"y\":3}";
    final MyPojo p = new MyPojo(2, 3);
    assertEquals(EXP_JSON, origWriter.writeValueAsString(p));
    String json = origWriter.writeValueAsString(new AnyBean().addEntry("a", "b"));
    assertNotNull(json);
    byte[] bytes = jdkSerialize(origWriter);
    ObjectWriter writer2 = jdkDeserialize(bytes);
    assertEquals(EXP_JSON, writer2.writeValueAsString(p));
}
Also used : ObjectWriter(com.fasterxml.jackson.databind.ObjectWriter)

Aggregations

ObjectWriter (com.fasterxml.jackson.databind.ObjectWriter)42 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)18 Test (org.junit.Test)12 JavaType (com.fasterxml.jackson.databind.JavaType)7 IOException (java.io.IOException)7 ObjectReader (com.fasterxml.jackson.databind.ObjectReader)4 FilterProvider (com.fasterxml.jackson.databind.ser.FilterProvider)4 SimpleFilterProvider (com.fasterxml.jackson.databind.ser.impl.SimpleFilterProvider)4 OutputStream (java.io.OutputStream)4 JsonGenerator (com.fasterxml.jackson.core.JsonGenerator)3 PluginTestVerifier (com.navercorp.pinpoint.bootstrap.plugin.test.PluginTestVerifier)3 FileOutputStream (java.io.FileOutputStream)3 Writer (java.io.Writer)3 JCommander (com.beust.jcommander.JCommander)2 ParameterException (com.beust.jcommander.ParameterException)2 JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)2 SerializationConfig (com.fasterxml.jackson.databind.SerializationConfig)2 RateLimiter (com.google.common.util.concurrent.RateLimiter)2 Application (com.navercorp.pinpoint.web.vo.Application)2 Range (com.navercorp.pinpoint.web.vo.Range)2