Search in sources :

Example 1 with PulsarDriverUnexpectedException

use of io.nosqlbench.driver.pulsar.exception.PulsarDriverUnexpectedException in project nosqlbench by nosqlbench.

the class PulsarProducerOp method run.

@Override
public void run(Runnable timeTracker) {
    if (StringUtils.isBlank(msgPayload)) {
        throw new PulsarDriverParamException("Message payload (\"msg-value\") can't be empty!");
    }
    TypedMessageBuilder typedMessageBuilder;
    final Transaction transaction;
    if (useTransaction) {
        // if you are in a transaction you cannot set the schema per-message
        transaction = transactionSupplier.get();
        typedMessageBuilder = producer.newMessage(transaction);
    } else {
        transaction = null;
        typedMessageBuilder = producer.newMessage(pulsarSchema);
    }
    // set message key
    if (!StringUtils.isBlank(msgKey)) {
        typedMessageBuilder = typedMessageBuilder.key(msgKey);
    }
    // set message properties
    if (!msgProperties.isEmpty()) {
        typedMessageBuilder = typedMessageBuilder.properties(msgProperties);
    }
    // set message payload
    int messageSize;
    SchemaType schemaType = pulsarSchema.getSchemaInfo().getType();
    if (pulsarSchema instanceof KeyValueSchema) {
        // {KEY IN JSON}||{VALUE IN JSON}
        int separator = msgPayload.indexOf("}||{");
        if (separator < 0) {
            throw new IllegalArgumentException("KeyValue payload MUST be in form {KEY IN JSON}||{VALUE IN JSON} (with 2 pipes that separate the KEY part from the VALUE part)");
        }
        String keyInput = msgPayload.substring(0, separator + 1);
        String valueInput = msgPayload.substring(separator + 3);
        KeyValueSchema keyValueSchema = (KeyValueSchema) pulsarSchema;
        org.apache.avro.Schema avroSchema = getAvroSchemaFromConfiguration();
        GenericRecord payload = AvroUtil.GetGenericRecord_PulsarAvro((GenericAvroSchema) keyValueSchema.getValueSchema(), avroSchema, valueInput);
        org.apache.avro.Schema avroSchemaForKey = getKeyAvroSchemaFromConfiguration();
        GenericRecord key = AvroUtil.GetGenericRecord_PulsarAvro((GenericAvroSchema) keyValueSchema.getKeySchema(), avroSchemaForKey, keyInput);
        typedMessageBuilder = typedMessageBuilder.value(new KeyValue(key, payload));
        // TODO: add a way to calculate the message size for KEY_VALUE messages
        messageSize = msgPayload.length();
    } else if (PulsarActivityUtil.isAvroSchemaTypeStr(schemaType.name())) {
        GenericRecord payload = AvroUtil.GetGenericRecord_PulsarAvro((GenericAvroSchema) pulsarSchema, pulsarSchema.getSchemaInfo().getSchemaDefinition(), msgPayload);
        typedMessageBuilder = typedMessageBuilder.value(payload);
        // TODO: add a way to calculate the message size for AVRO messages
        messageSize = msgPayload.length();
    } else {
        byte[] array = msgPayload.getBytes(StandardCharsets.UTF_8);
        typedMessageBuilder = typedMessageBuilder.value(array);
        messageSize = array.length;
    }
    messageSizeHistogram.update(messageSize);
    bytesCounter.inc(messageSize);
    // TODO: add error handling with failed message production
    if (!asyncPulsarOp) {
        try {
            logger.trace("Sending message");
            typedMessageBuilder.send();
            if (useTransaction) {
                try (Timer.Context ctx = transactionCommitTimer.time()) {
                    transaction.commit().get();
                }
            }
            if (logger.isDebugEnabled()) {
                if (PulsarActivityUtil.isAvroSchemaTypeStr(schemaType.name())) {
                    org.apache.avro.Schema avroSchema = getAvroSchemaFromConfiguration();
                    org.apache.avro.generic.GenericRecord avroGenericRecord = AvroUtil.GetGenericRecord_ApacheAvro(avroSchema, msgPayload);
                    logger.debug("({}) Sync message sent: msg-key={}; msg-properties={}; msg-payload={})", producer.getProducerName(), msgKey, msgProperties, avroGenericRecord.toString());
                } else {
                    logger.debug("({}) Sync message sent; msg-key={}; msg-properties={}; msg-payload={}", producer.getProducerName(), msgKey, msgProperties, msgPayload);
                }
            }
        } catch (PulsarClientException | ExecutionException | InterruptedException pce) {
            String errMsg = "Sync message sending failed: " + "key - " + msgKey + "; " + "properties - " + msgProperties + "; " + "payload - " + msgPayload;
            logger.trace(errMsg);
            throw new PulsarDriverUnexpectedException(errMsg);
        }
        timeTracker.run();
    } else {
        try {
            // we rely on blockIfQueueIsFull in order to throttle the request in this case
            CompletableFuture<?> future = typedMessageBuilder.sendAsync();
            if (useTransaction) {
                // add commit step
                future = future.thenCompose(msg -> {
                    Timer.Context ctx = transactionCommitTimer.time();
                    return transaction.commit().whenComplete((m, e) -> ctx.close()).thenApply(v -> msg);
                });
            }
            future.whenComplete((messageId, error) -> {
                if (logger.isDebugEnabled()) {
                    if (PulsarActivityUtil.isAvroSchemaTypeStr(schemaType.name())) {
                        org.apache.avro.Schema avroSchema = getAvroSchemaFromConfiguration();
                        org.apache.avro.generic.GenericRecord avroGenericRecord = AvroUtil.GetGenericRecord_ApacheAvro(avroSchema, msgPayload);
                        logger.debug("({}) Aysnc message sent: msg-key={}; msg-properties={}; msg-payload={})", producer.getProducerName(), msgKey, msgProperties, avroGenericRecord.toString());
                    } else {
                        logger.debug("({}) Aysnc message sent: msg-key={}; msg-properties={}; msg-payload={}", producer.getProducerName(), msgKey, msgProperties, msgPayload);
                    }
                }
                timeTracker.run();
            }).exceptionally(ex -> {
                logger.error("Async message sending failed: " + "key - " + msgKey + "; " + "properties - " + msgProperties + "; " + "payload - " + msgPayload);
                pulsarActivity.asyncOperationFailed(ex);
                return null;
            });
        } catch (Exception e) {
            throw new PulsarDriverUnexpectedException(e);
        }
    }
}
Also used : Histogram(com.codahale.metrics.Histogram) org.apache.pulsar.client.api(org.apache.pulsar.client.api) CompletableFuture(java.util.concurrent.CompletableFuture) PulsarActivity(io.nosqlbench.driver.pulsar.PulsarActivity) StringUtils(org.apache.commons.lang3.StringUtils) Supplier(java.util.function.Supplier) Transaction(org.apache.pulsar.client.api.transaction.Transaction) SchemaType(org.apache.pulsar.common.schema.SchemaType) StandardCharsets(java.nio.charset.StandardCharsets) PulsarDriverParamException(io.nosqlbench.driver.pulsar.exception.PulsarDriverParamException) GenericRecord(org.apache.pulsar.client.api.schema.GenericRecord) KeyValue(org.apache.pulsar.common.schema.KeyValue) ExecutionException(java.util.concurrent.ExecutionException) PulsarDriverUnexpectedException(io.nosqlbench.driver.pulsar.exception.PulsarDriverUnexpectedException) Logger(org.apache.logging.log4j.Logger) PulsarActivityUtil(io.nosqlbench.driver.pulsar.util.PulsarActivityUtil) AvroUtil(io.nosqlbench.driver.pulsar.util.AvroUtil) Map(java.util.Map) Counter(com.codahale.metrics.Counter) GenericAvroSchema(org.apache.pulsar.client.impl.schema.generic.GenericAvroSchema) Timer(com.codahale.metrics.Timer) KeyValueSchema(org.apache.pulsar.client.api.schema.KeyValueSchema) LogManager(org.apache.logging.log4j.LogManager) KeyValue(org.apache.pulsar.common.schema.KeyValue) GenericAvroSchema(org.apache.pulsar.client.impl.schema.generic.GenericAvroSchema) KeyValueSchema(org.apache.pulsar.client.api.schema.KeyValueSchema) SchemaType(org.apache.pulsar.common.schema.SchemaType) GenericRecord(org.apache.pulsar.client.api.schema.GenericRecord) ExecutionException(java.util.concurrent.ExecutionException) KeyValueSchema(org.apache.pulsar.client.api.schema.KeyValueSchema) GenericAvroSchema(org.apache.pulsar.client.impl.schema.generic.GenericAvroSchema) PulsarDriverParamException(io.nosqlbench.driver.pulsar.exception.PulsarDriverParamException) ExecutionException(java.util.concurrent.ExecutionException) PulsarDriverUnexpectedException(io.nosqlbench.driver.pulsar.exception.PulsarDriverUnexpectedException) PulsarDriverParamException(io.nosqlbench.driver.pulsar.exception.PulsarDriverParamException) PulsarDriverUnexpectedException(io.nosqlbench.driver.pulsar.exception.PulsarDriverUnexpectedException) Transaction(org.apache.pulsar.client.api.transaction.Transaction) Timer(com.codahale.metrics.Timer)

Example 2 with PulsarDriverUnexpectedException

use of io.nosqlbench.driver.pulsar.exception.PulsarDriverUnexpectedException in project nosqlbench by nosqlbench.

the class PulsarConsumerOp method run.

@Override
public void run(Runnable timeTracker) {
    final Transaction transaction;
    if (useTransaction) {
        // if you are in a transaction you cannot set the schema per-message
        transaction = transactionSupplier.get();
    } else {
        transaction = null;
    }
    if (!asyncPulsarOp) {
        try {
            Message<?> message;
            if (timeoutSeconds <= 0) {
                // wait forever
                message = consumer.receive();
            } else {
                message = consumer.receive(timeoutSeconds, TimeUnit.SECONDS);
                if (message == null) {
                    throw new TimeoutException("Did not receive a message within " + timeoutSeconds + " seconds");
                }
            }
            handleMessage(transaction, message);
        } catch (Exception e) {
            logger.error("Sync message receiving failed - timeout value: {} seconds ", timeoutSeconds, e);
            throw new PulsarDriverUnexpectedException("" + "Sync message receiving failed - timeout value: " + timeoutSeconds + " seconds ");
        }
    } else {
        try {
            CompletableFuture<? extends Message<?>> msgRecvFuture = consumer.receiveAsync();
            if (useTransaction) {
                // add commit step
                msgRecvFuture = msgRecvFuture.thenCompose(msg -> {
                    Timer.Context ctx = transactionCommitTimer.time();
                    return transaction.commit().whenComplete((m, e) -> ctx.close()).thenApply(v -> msg);
                });
            }
            msgRecvFuture.thenAccept(message -> {
                try {
                    handleMessage(transaction, message);
                } catch (PulsarClientException | TimeoutException e) {
                    pulsarActivity.asyncOperationFailed(e);
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                } catch (ExecutionException e) {
                    pulsarActivity.asyncOperationFailed(e.getCause());
                }
            }).exceptionally(ex -> {
                pulsarActivity.asyncOperationFailed(ex);
                return null;
            });
        } catch (Exception e) {
            throw new PulsarDriverUnexpectedException(e);
        }
    }
}
Also used : Histogram(com.codahale.metrics.Histogram) org.apache.pulsar.client.api(org.apache.pulsar.client.api) TimeoutException(java.util.concurrent.TimeoutException) CompletableFuture(java.util.concurrent.CompletableFuture) Function(java.util.function.Function) Supplier(java.util.function.Supplier) StringUtils(org.apache.commons.lang3.StringUtils) PulsarActivity(io.nosqlbench.driver.pulsar.PulsarActivity) GsonBuilder(com.google.gson.GsonBuilder) Transaction(org.apache.pulsar.client.api.transaction.Transaction) SchemaType(org.apache.pulsar.common.schema.SchemaType) ExecutionException(java.util.concurrent.ExecutionException) TimeUnit(java.util.concurrent.TimeUnit) GenericRecord(org.apache.pulsar.client.api.schema.GenericRecord) PulsarDriverUnexpectedException(io.nosqlbench.driver.pulsar.exception.PulsarDriverUnexpectedException) Logger(org.apache.logging.log4j.Logger) PulsarActivityUtil(io.nosqlbench.driver.pulsar.util.PulsarActivityUtil) Gson(com.google.gson.Gson) AvroUtil(io.nosqlbench.driver.pulsar.util.AvroUtil) Counter(com.codahale.metrics.Counter) Timer(com.codahale.metrics.Timer) LogManager(org.apache.logging.log4j.LogManager) PulsarDriverUnexpectedException(io.nosqlbench.driver.pulsar.exception.PulsarDriverUnexpectedException) Transaction(org.apache.pulsar.client.api.transaction.Transaction) ExecutionException(java.util.concurrent.ExecutionException) TimeoutException(java.util.concurrent.TimeoutException) ExecutionException(java.util.concurrent.ExecutionException) PulsarDriverUnexpectedException(io.nosqlbench.driver.pulsar.exception.PulsarDriverUnexpectedException) TimeoutException(java.util.concurrent.TimeoutException)

Aggregations

Counter (com.codahale.metrics.Counter)2 Histogram (com.codahale.metrics.Histogram)2 Timer (com.codahale.metrics.Timer)2 PulsarActivity (io.nosqlbench.driver.pulsar.PulsarActivity)2 PulsarDriverUnexpectedException (io.nosqlbench.driver.pulsar.exception.PulsarDriverUnexpectedException)2 AvroUtil (io.nosqlbench.driver.pulsar.util.AvroUtil)2 PulsarActivityUtil (io.nosqlbench.driver.pulsar.util.PulsarActivityUtil)2 CompletableFuture (java.util.concurrent.CompletableFuture)2 ExecutionException (java.util.concurrent.ExecutionException)2 Supplier (java.util.function.Supplier)2 StringUtils (org.apache.commons.lang3.StringUtils)2 LogManager (org.apache.logging.log4j.LogManager)2 Logger (org.apache.logging.log4j.Logger)2 org.apache.pulsar.client.api (org.apache.pulsar.client.api)2 GenericRecord (org.apache.pulsar.client.api.schema.GenericRecord)2 Transaction (org.apache.pulsar.client.api.transaction.Transaction)2 SchemaType (org.apache.pulsar.common.schema.SchemaType)2 Gson (com.google.gson.Gson)1 GsonBuilder (com.google.gson.GsonBuilder)1 PulsarDriverParamException (io.nosqlbench.driver.pulsar.exception.PulsarDriverParamException)1