Search in sources :

Example 1 with AuthenticationDataProvider

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

the class PerformanceClient method runPerformanceTest.

public void runPerformanceTest(long messages, long limit, int numOfTopic, int sizeOfMessage, String baseUrl, String topicName, String authPluginClassName, String authParams) throws InterruptedException, FileNotFoundException {
    ExecutorService executor = Executors.newCachedThreadPool(new DefaultThreadFactory("pulsar-perf-producer-exec"));
    HashMap<String, Tuple> producersMap = new HashMap<>();
    String produceBaseEndPoint = baseUrl + "ws/producer" + topicName;
    for (int i = 0; i < numOfTopic; i++) {
        String topic = numOfTopic > 1 ? produceBaseEndPoint + String.valueOf(i) : produceBaseEndPoint;
        URI produceUri = URI.create(topic);
        WebSocketClient produceClient = new WebSocketClient(new SslContextFactory(true));
        ClientUpgradeRequest produceRequest = new ClientUpgradeRequest();
        if (StringUtils.isNotBlank(authPluginClassName) && StringUtils.isNotBlank(authParams)) {
            try {
                Authentication auth = AuthenticationFactory.create(authPluginClassName, authParams);
                auth.start();
                AuthenticationDataProvider authData = auth.getAuthData();
                if (authData.hasDataForHttp()) {
                    for (Map.Entry<String, String> kv : authData.getHttpHeaders()) {
                        produceRequest.setHeader(kv.getKey(), kv.getValue());
                    }
                }
            } catch (Exception e) {
                log.error("Authentication plugin error: " + e.getMessage());
            }
        }
        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.valueOf(totalSent++), sizeOfMessage);
                    messagesSent.increment();
                    bytesSent.add(sizeOfMessage);
                }
            }
        } 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 {} \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 : Histogram(org.HdrHistogram.Histogram) AuthenticationDataProvider(org.apache.pulsar.client.api.AuthenticationDataProvider) HashMap(java.util.HashMap) URI(java.net.URI) DefaultThreadFactory(io.netty.util.concurrent.DefaultThreadFactory) SslContextFactory(org.eclipse.jetty.util.ssl.SslContextFactory) HistogramLogWriter(org.HdrHistogram.HistogramLogWriter) PrintStream(java.io.PrintStream) IOException(java.io.IOException) WebSocketClient(org.eclipse.jetty.websocket.client.WebSocketClient) ParameterException(com.beust.jcommander.ParameterException) IOException(java.io.IOException) FileNotFoundException(java.io.FileNotFoundException) RateLimiter(com.google.common.util.concurrent.RateLimiter) Authentication(org.apache.pulsar.client.api.Authentication) FileOutputStream(java.io.FileOutputStream) ExecutorService(java.util.concurrent.ExecutorService) ClientUpgradeRequest(org.eclipse.jetty.websocket.client.ClientUpgradeRequest) HashMap(java.util.HashMap) Map(java.util.Map)

Example 2 with AuthenticationDataProvider

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

the class HttpClient method get.

public <T> CompletableFuture<T> get(String path, Class<T> clazz) {
    final CompletableFuture<T> future = new CompletableFuture<>();
    try {
        String requestUrl = new URL(url, path).toString();
        AuthenticationDataProvider authData = authentication.getAuthData();
        BoundRequestBuilder builder = httpClient.prepareGet(requestUrl);
        // Add headers for authentication if any
        if (authData.hasDataForHttp()) {
            for (Map.Entry<String, String> header : authData.getHttpHeaders()) {
                builder.setHeader(header.getKey(), header.getValue());
            }
        }
        final ListenableFuture<Response> responseFuture = builder.setHeader("Accept", "application/json").execute(new AsyncCompletionHandler<Response>() {

            @Override
            public Response onCompleted(Response response) throws Exception {
                return response;
            }

            @Override
            public void onThrowable(Throwable t) {
                log.warn("[{}] Failed to perform http request: {}", requestUrl, t.getMessage());
                future.completeExceptionally(new PulsarClientException(t));
            }
        });
        responseFuture.addListener(() -> {
            try {
                Response response = responseFuture.get();
                if (response.getStatusCode() != HttpURLConnection.HTTP_OK) {
                    log.warn("[{}] HTTP get request failed: {}", requestUrl, response.getStatusText());
                    future.completeExceptionally(new PulsarClientException("HTTP get request failed: " + response.getStatusText()));
                    return;
                }
                T data = ObjectMapperFactory.getThreadLocal().readValue(response.getResponseBodyAsBytes(), clazz);
                future.complete(data);
            } catch (Exception e) {
                log.warn("[{}] Error during HTTP get request: {}", requestUrl, e.getMessage());
                future.completeExceptionally(new PulsarClientException(e));
            }
        }, MoreExecutors.directExecutor());
    } catch (Exception e) {
        log.warn("[{}] Failed to get authentication data for lookup: {}", path, e.getMessage());
        if (e instanceof PulsarClientException) {
            future.completeExceptionally(e);
        } else {
            future.completeExceptionally(new PulsarClientException(e));
        }
    }
    return future;
}
Also used : AuthenticationDataProvider(org.apache.pulsar.client.api.AuthenticationDataProvider) URL(java.net.URL) PulsarClientException(org.apache.pulsar.client.api.PulsarClientException) MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException) Response(org.asynchttpclient.Response) HttpResponse(io.netty.handler.codec.http.HttpResponse) BoundRequestBuilder(org.asynchttpclient.BoundRequestBuilder) CompletableFuture(java.util.concurrent.CompletableFuture) PulsarClientException(org.apache.pulsar.client.api.PulsarClientException) Map(java.util.Map)

Aggregations

IOException (java.io.IOException)2 Map (java.util.Map)2 AuthenticationDataProvider (org.apache.pulsar.client.api.AuthenticationDataProvider)2 ParameterException (com.beust.jcommander.ParameterException)1 RateLimiter (com.google.common.util.concurrent.RateLimiter)1 HttpResponse (io.netty.handler.codec.http.HttpResponse)1 DefaultThreadFactory (io.netty.util.concurrent.DefaultThreadFactory)1 FileNotFoundException (java.io.FileNotFoundException)1 FileOutputStream (java.io.FileOutputStream)1 PrintStream (java.io.PrintStream)1 MalformedURLException (java.net.MalformedURLException)1 URI (java.net.URI)1 URL (java.net.URL)1 HashMap (java.util.HashMap)1 CompletableFuture (java.util.concurrent.CompletableFuture)1 ExecutorService (java.util.concurrent.ExecutorService)1 Histogram (org.HdrHistogram.Histogram)1 HistogramLogWriter (org.HdrHistogram.HistogramLogWriter)1 Authentication (org.apache.pulsar.client.api.Authentication)1 PulsarClientException (org.apache.pulsar.client.api.PulsarClientException)1