Search in sources :

Example 26 with Callback

use of org.apache.kafka.clients.producer.Callback in project flink by apache.

the class FlinkKafkaProducerBase method open.

// ----------------------------------- Utilities --------------------------
/**
 * Initializes the connection to Kafka.
 */
@Override
public void open(Configuration configuration) throws Exception {
    if (schema instanceof KeyedSerializationSchemaWrapper) {
        ((KeyedSerializationSchemaWrapper<IN>) schema).getSerializationSchema().open(RuntimeContextInitializationContextAdapters.serializationAdapter(getRuntimeContext(), metricGroup -> metricGroup.addGroup("user")));
    }
    producer = getKafkaProducer(this.producerConfig);
    RuntimeContext ctx = getRuntimeContext();
    if (null != flinkKafkaPartitioner) {
        flinkKafkaPartitioner.open(ctx.getIndexOfThisSubtask(), ctx.getNumberOfParallelSubtasks());
    }
    LOG.info("Starting FlinkKafkaProducer ({}/{}) to produce into default topic {}", ctx.getIndexOfThisSubtask() + 1, ctx.getNumberOfParallelSubtasks(), defaultTopicId);
    // register Kafka metrics to Flink accumulators
    if (!Boolean.parseBoolean(producerConfig.getProperty(KEY_DISABLE_METRICS, "false"))) {
        Map<MetricName, ? extends Metric> metrics = this.producer.metrics();
        if (metrics == null) {
            // MapR's Kafka implementation returns null here.
            LOG.info("Producer implementation does not support metrics");
        } else {
            final MetricGroup kafkaMetricGroup = getRuntimeContext().getMetricGroup().addGroup("KafkaProducer");
            for (Map.Entry<MetricName, ? extends Metric> metric : metrics.entrySet()) {
                kafkaMetricGroup.gauge(metric.getKey().name(), new KafkaMetricWrapper(metric.getValue()));
            }
        }
    }
    if (flushOnCheckpoint && !((StreamingRuntimeContext) this.getRuntimeContext()).isCheckpointingEnabled()) {
        LOG.warn("Flushing on checkpoint is enabled, but checkpointing is not enabled. Disabling flushing.");
        flushOnCheckpoint = false;
    }
    if (logFailuresOnly) {
        callback = new Callback() {

            @Override
            public void onCompletion(RecordMetadata metadata, Exception e) {
                if (e != null) {
                    LOG.error("Error while sending record to Kafka: " + e.getMessage(), e);
                }
                acknowledgeMessage();
            }
        };
    } else {
        callback = new Callback() {

            @Override
            public void onCompletion(RecordMetadata metadata, Exception exception) {
                if (exception != null && asyncException == null) {
                    asyncException = exception;
                }
                acknowledgeMessage();
            }
        };
    }
}
Also used : RuntimeContext(org.apache.flink.api.common.functions.RuntimeContext) ProducerRecord(org.apache.kafka.clients.producer.ProducerRecord) KeyedSerializationSchemaWrapper(org.apache.flink.streaming.connectors.kafka.internals.KeyedSerializationSchemaWrapper) LoggerFactory(org.slf4j.LoggerFactory) HashMap(java.util.HashMap) RuntimeContextInitializationContextAdapters(org.apache.flink.api.common.serialization.RuntimeContextInitializationContextAdapters) FunctionSnapshotContext(org.apache.flink.runtime.state.FunctionSnapshotContext) NetUtils(org.apache.flink.util.NetUtils) ArrayList(java.util.ArrayList) KafkaMetricWrapper(org.apache.flink.streaming.connectors.kafka.internals.metrics.KafkaMetricWrapper) KafkaProducer(org.apache.kafka.clients.producer.KafkaProducer) ByteArraySerializer(org.apache.kafka.common.serialization.ByteArraySerializer) Map(java.util.Map) Objects.requireNonNull(java.util.Objects.requireNonNull) Metric(org.apache.kafka.common.Metric) MetricName(org.apache.kafka.common.MetricName) ProducerConfig(org.apache.kafka.clients.producer.ProducerConfig) Logger(org.slf4j.Logger) Properties(java.util.Properties) CheckpointedFunction(org.apache.flink.streaming.api.checkpoint.CheckpointedFunction) FunctionInitializationContext(org.apache.flink.runtime.state.FunctionInitializationContext) Configuration(org.apache.flink.configuration.Configuration) PartitionInfo(org.apache.kafka.common.PartitionInfo) RecordMetadata(org.apache.kafka.clients.producer.RecordMetadata) FlinkKafkaPartitioner(org.apache.flink.streaming.connectors.kafka.partitioner.FlinkKafkaPartitioner) KeyedSerializationSchema(org.apache.flink.streaming.util.serialization.KeyedSerializationSchema) RichSinkFunction(org.apache.flink.streaming.api.functions.sink.RichSinkFunction) VisibleForTesting(org.apache.flink.annotation.VisibleForTesting) SerializableObject(org.apache.flink.util.SerializableObject) MetricGroup(org.apache.flink.metrics.MetricGroup) List(java.util.List) ExecutionConfig(org.apache.flink.api.common.ExecutionConfig) Internal(org.apache.flink.annotation.Internal) ClosureCleaner(org.apache.flink.api.java.ClosureCleaner) Comparator(java.util.Comparator) StreamingRuntimeContext(org.apache.flink.streaming.api.operators.StreamingRuntimeContext) Callback(org.apache.kafka.clients.producer.Callback) Collections(java.util.Collections) StreamingRuntimeContext(org.apache.flink.streaming.api.operators.StreamingRuntimeContext) KeyedSerializationSchemaWrapper(org.apache.flink.streaming.connectors.kafka.internals.KeyedSerializationSchemaWrapper) MetricGroup(org.apache.flink.metrics.MetricGroup) RecordMetadata(org.apache.kafka.clients.producer.RecordMetadata) MetricName(org.apache.kafka.common.MetricName) Callback(org.apache.kafka.clients.producer.Callback) KafkaMetricWrapper(org.apache.flink.streaming.connectors.kafka.internals.metrics.KafkaMetricWrapper) RuntimeContext(org.apache.flink.api.common.functions.RuntimeContext) StreamingRuntimeContext(org.apache.flink.streaming.api.operators.StreamingRuntimeContext) HashMap(java.util.HashMap) Map(java.util.Map)

Example 27 with Callback

use of org.apache.kafka.clients.producer.Callback in project flink by apache.

the class KafkaTestBase method produceToKafka.

public static <K, V> void produceToKafka(Collection<ProducerRecord<K, V>> records, Class<? extends org.apache.kafka.common.serialization.Serializer<K>> keySerializerClass, Class<? extends org.apache.kafka.common.serialization.Serializer<V>> valueSerializerClass) throws Throwable {
    Properties props = new Properties();
    props.putAll(standardProps);
    props.putAll(kafkaServer.getIdempotentProducerConfig());
    props.setProperty(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, keySerializerClass.getName());
    props.setProperty(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, valueSerializerClass.getName());
    AtomicReference<Throwable> sendingError = new AtomicReference<>();
    Callback callback = (metadata, exception) -> {
        if (exception != null) {
            if (!sendingError.compareAndSet(null, exception)) {
                sendingError.get().addSuppressed(exception);
            }
        }
    };
    try (KafkaProducer<K, V> producer = new KafkaProducer<>(props)) {
        for (ProducerRecord<K, V> record : records) {
            producer.send(record, callback);
        }
    }
    if (sendingError.get() != null) {
        throw sendingError.get();
    }
}
Also used : ProgramInvocationException(org.apache.flink.client.program.ProgramInvocationException) ProducerRecord(org.apache.kafka.clients.producer.ProducerRecord) BeforeClass(org.junit.BeforeClass) LoggerFactory(org.slf4j.LoggerFactory) AtomicReference(java.util.concurrent.atomic.AtomicReference) MemorySize(org.apache.flink.configuration.MemorySize) ByteBuffer(java.nio.ByteBuffer) SuccessException(org.apache.flink.test.util.SuccessException) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) TaskManagerOptions(org.apache.flink.configuration.TaskManagerOptions) InstantiationUtil(org.apache.flink.util.InstantiationUtil) KafkaProducer(org.apache.kafka.clients.producer.KafkaProducer) ConfigConstants(org.apache.flink.configuration.ConfigConstants) TestLogger(org.apache.flink.util.TestLogger) Assert.fail(org.junit.Assert.fail) JobExecutionException(org.apache.flink.runtime.client.JobExecutionException) RetryRule(org.apache.flink.testutils.junit.RetryRule) ClassRule(org.junit.ClassRule) RetryOnFailure(org.apache.flink.testutils.junit.RetryOnFailure) ProducerConfig(org.apache.kafka.clients.producer.ProducerConfig) AfterClass(org.junit.AfterClass) Logger(org.slf4j.Logger) Properties(java.util.Properties) FiniteDuration(scala.concurrent.duration.FiniteDuration) Collection(java.util.Collection) Configuration(org.apache.flink.configuration.Configuration) Set(java.util.Set) TimeUnit(java.util.concurrent.TimeUnit) List(java.util.List) Rule(org.junit.Rule) TestStreamEnvironment(org.apache.flink.streaming.util.TestStreamEnvironment) ConsumerRecord(org.apache.kafka.clients.consumer.ConsumerRecord) JMXReporter(org.apache.flink.metrics.jmx.JMXReporter) Callback(org.apache.kafka.clients.producer.Callback) TemporaryFolder(org.junit.rules.TemporaryFolder) StreamExecutionEnvironment(org.apache.flink.streaming.api.environment.StreamExecutionEnvironment) KafkaProducer(org.apache.kafka.clients.producer.KafkaProducer) Callback(org.apache.kafka.clients.producer.Callback) AtomicReference(java.util.concurrent.atomic.AtomicReference) Properties(java.util.Properties)

Example 28 with Callback

use of org.apache.kafka.clients.producer.Callback in project kafka by apache.

the class SenderTest method testAppendInExpiryCallback.

@Test
public void testAppendInExpiryCallback() throws InterruptedException {
    int messagesPerBatch = 10;
    final AtomicInteger expiryCallbackCount = new AtomicInteger(0);
    final AtomicReference<Exception> unexpectedException = new AtomicReference<>();
    final byte[] key = "key".getBytes();
    final byte[] value = "value".getBytes();
    final long maxBlockTimeMs = 1000;
    Callback callback = (metadata, exception) -> {
        if (exception instanceof TimeoutException) {
            expiryCallbackCount.incrementAndGet();
            try {
                accumulator.append(tp1, 0L, key, value, Record.EMPTY_HEADERS, null, maxBlockTimeMs, false, time.milliseconds());
            } catch (InterruptedException e) {
                throw new RuntimeException("Unexpected interruption", e);
            }
        } else if (exception != null)
            unexpectedException.compareAndSet(null, exception);
    };
    final long nowMs = time.milliseconds();
    for (int i = 0; i < messagesPerBatch; i++) accumulator.append(tp1, 0L, key, value, null, callback, maxBlockTimeMs, false, nowMs);
    // Advance the clock to expire the first batch.
    time.sleep(10000);
    Node clusterNode = metadata.fetch().nodes().get(0);
    Map<Integer, List<ProducerBatch>> drainedBatches = accumulator.drain(metadata.fetch(), Collections.singleton(clusterNode), Integer.MAX_VALUE, time.milliseconds());
    sender.addToInflightBatches(drainedBatches);
    // Disconnect the target node for the pending produce request. This will ensure that sender will try to
    // expire the batch.
    client.disconnect(clusterNode.idString());
    client.backoff(clusterNode, 100);
    // We should try to flush the batch, but we expire it instead without sending anything.
    sender.runOnce();
    assertEquals(messagesPerBatch, expiryCallbackCount.get(), "Callbacks not invoked for expiry");
    assertNull(unexpectedException.get(), "Unexpected exception");
    // Make sure that the reconds were appended back to the batch.
    assertTrue(accumulator.batches().containsKey(tp1));
    assertEquals(1, accumulator.batches().get(tp1).size());
    assertEquals(messagesPerBatch, accumulator.batches().get(tp1).peekFirst().recordCount);
}
Also used : BeforeEach(org.junit.jupiter.api.BeforeEach) MockTime(org.apache.kafka.common.utils.MockTime) Arrays(java.util.Arrays) TransactionAbortedException(org.apache.kafka.common.errors.TransactionAbortedException) ArgumentMatchers.eq(org.mockito.ArgumentMatchers.eq) KafkaException(org.apache.kafka.common.KafkaException) Cluster(org.apache.kafka.common.Cluster) Future(java.util.concurrent.Future) ApiVersionsResponse(org.apache.kafka.common.requests.ApiVersionsResponse) RecordBatch(org.apache.kafka.common.record.RecordBatch) LogContext(org.apache.kafka.common.utils.LogContext) Map(java.util.Map) MutableRecordBatch(org.apache.kafka.common.record.MutableRecordBatch) ProduceResponseData(org.apache.kafka.common.message.ProduceResponseData) Sensor(org.apache.kafka.common.metrics.Sensor) CompressionType(org.apache.kafka.common.record.CompressionType) TestUtils(org.apache.kafka.test.TestUtils) Mockito.atLeastOnce(org.mockito.Mockito.atLeastOnce) Set(java.util.Set) RecordMetadata(org.apache.kafka.clients.producer.RecordMetadata) MemoryRecords(org.apache.kafka.common.record.MemoryRecords) Metrics(org.apache.kafka.common.metrics.Metrics) ApiMessageType(org.apache.kafka.common.message.ApiMessageType) UnsupportedForMessageFormatException(org.apache.kafka.common.errors.UnsupportedForMessageFormatException) Assertions.assertTrue(org.junit.jupiter.api.Assertions.assertTrue) ProducerIdAndEpoch(org.apache.kafka.common.utils.ProducerIdAndEpoch) Errors(org.apache.kafka.common.protocol.Errors) Node(org.apache.kafka.common.Node) MetadataResponse(org.apache.kafka.common.requests.MetadataResponse) AdditionalMatchers.geq(org.mockito.AdditionalMatchers.geq) NodeApiVersions(org.apache.kafka.clients.NodeApiVersions) Assertions.assertThrows(org.junit.jupiter.api.Assertions.assertThrows) Assertions.fail(org.junit.jupiter.api.Assertions.fail) Assertions.assertNotNull(org.junit.jupiter.api.Assertions.assertNotNull) BatchIndexAndErrorMessage(org.apache.kafka.common.message.ProduceResponseData.BatchIndexAndErrorMessage) Assertions.assertNull(org.junit.jupiter.api.Assertions.assertNull) RequestTestUtils(org.apache.kafka.common.requests.RequestTestUtils) ArgumentMatchers.anyBoolean(org.mockito.ArgumentMatchers.anyBoolean) Mockito.spy(org.mockito.Mockito.spy) LinkedHashMap(java.util.LinkedHashMap) CoordinatorType(org.apache.kafka.common.requests.FindCoordinatorRequest.CoordinatorType) OptionalLong(java.util.OptionalLong) EndTxnResponseData(org.apache.kafka.common.message.EndTxnResponseData) NetworkClient(org.apache.kafka.clients.NetworkClient) Assertions.assertEquals(org.junit.jupiter.api.Assertions.assertEquals) ProduceResponse(org.apache.kafka.common.requests.ProduceResponse) CompressionRatioEstimator(org.apache.kafka.common.record.CompressionRatioEstimator) MockSelector(org.apache.kafka.test.MockSelector) Mockito.times(org.mockito.Mockito.times) ApiVersions(org.apache.kafka.clients.ApiVersions) Assertions.assertSame(org.junit.jupiter.api.Assertions.assertSame) MetricNameTemplate(org.apache.kafka.common.MetricNameTemplate) ExecutionException(java.util.concurrent.ExecutionException) AfterEach(org.junit.jupiter.api.AfterEach) NetworkReceive(org.apache.kafka.common.network.NetworkReceive) UnsupportedVersionException(org.apache.kafka.common.errors.UnsupportedVersionException) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) FindCoordinatorResponse(org.apache.kafka.common.requests.FindCoordinatorResponse) InitProducerIdRequest(org.apache.kafka.common.requests.InitProducerIdRequest) ProduceRequest(org.apache.kafka.common.requests.ProduceRequest) AbstractRequest(org.apache.kafka.common.requests.AbstractRequest) ClusterAuthorizationException(org.apache.kafka.common.errors.ClusterAuthorizationException) AddPartitionsToTxnResponse(org.apache.kafka.common.requests.AddPartitionsToTxnResponse) ByteBuffer(java.nio.ByteBuffer) ClientRequest(org.apache.kafka.clients.ClientRequest) Record(org.apache.kafka.common.record.Record) Assertions.assertFalse(org.junit.jupiter.api.Assertions.assertFalse) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) MetricName(org.apache.kafka.common.MetricName) ProducerTestUtils.runUntil(org.apache.kafka.clients.producer.internals.ProducerTestUtils.runUntil) TopicPartition(org.apache.kafka.common.TopicPartition) InitProducerIdResponseData(org.apache.kafka.common.message.InitProducerIdResponseData) IdentityHashMap(java.util.IdentityHashMap) Time(org.apache.kafka.common.utils.Time) EndTxnResponse(org.apache.kafka.common.requests.EndTxnResponse) MetricConfig(org.apache.kafka.common.metrics.MetricConfig) ClusterResourceListeners(org.apache.kafka.common.internals.ClusterResourceListeners) Test(org.junit.jupiter.api.Test) List(java.util.List) InitProducerIdResponse(org.apache.kafka.common.requests.InitProducerIdResponse) Mockito.inOrder(org.mockito.Mockito.inOrder) RecordTooLargeException(org.apache.kafka.common.errors.RecordTooLargeException) KafkaMetric(org.apache.kafka.common.metrics.KafkaMetric) Callback(org.apache.kafka.clients.producer.Callback) ClientResponse(org.apache.kafka.clients.ClientResponse) ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) ArgumentMatchers.anyLong(org.mockito.ArgumentMatchers.anyLong) NetworkException(org.apache.kafka.common.errors.NetworkException) HashMap(java.util.HashMap) Deque(java.util.Deque) OptionalInt(java.util.OptionalInt) AtomicReference(java.util.concurrent.atomic.AtomicReference) InvalidRecordException(org.apache.kafka.common.InvalidRecordException) HashSet(java.util.HashSet) EndTxnRequest(org.apache.kafka.common.requests.EndTxnRequest) MetadataRequest(org.apache.kafka.common.requests.MetadataRequest) ProduceRequestData(org.apache.kafka.common.message.ProduceRequestData) ArgumentMatchers.anyInt(org.mockito.ArgumentMatchers.anyInt) TimeoutException(org.apache.kafka.common.errors.TimeoutException) MockClient(org.apache.kafka.clients.MockClient) InOrder(org.mockito.InOrder) Iterator(java.util.Iterator) TransactionResult(org.apache.kafka.common.requests.TransactionResult) ApiKeys(org.apache.kafka.common.protocol.ApiKeys) Mockito.verify(org.mockito.Mockito.verify) TimeUnit(java.util.concurrent.TimeUnit) DelayedReceive(org.apache.kafka.test.DelayedReceive) TopicAuthorizationException(org.apache.kafka.common.errors.TopicAuthorizationException) InvalidRequestException(org.apache.kafka.common.errors.InvalidRequestException) Timeout(org.junit.jupiter.api.Timeout) Collections(java.util.Collections) Node(org.apache.kafka.common.Node) AtomicReference(java.util.concurrent.atomic.AtomicReference) TransactionAbortedException(org.apache.kafka.common.errors.TransactionAbortedException) KafkaException(org.apache.kafka.common.KafkaException) UnsupportedForMessageFormatException(org.apache.kafka.common.errors.UnsupportedForMessageFormatException) ExecutionException(java.util.concurrent.ExecutionException) UnsupportedVersionException(org.apache.kafka.common.errors.UnsupportedVersionException) ClusterAuthorizationException(org.apache.kafka.common.errors.ClusterAuthorizationException) RecordTooLargeException(org.apache.kafka.common.errors.RecordTooLargeException) NetworkException(org.apache.kafka.common.errors.NetworkException) InvalidRecordException(org.apache.kafka.common.InvalidRecordException) TimeoutException(org.apache.kafka.common.errors.TimeoutException) TopicAuthorizationException(org.apache.kafka.common.errors.TopicAuthorizationException) InvalidRequestException(org.apache.kafka.common.errors.InvalidRequestException) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Callback(org.apache.kafka.clients.producer.Callback) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) List(java.util.List) TimeoutException(org.apache.kafka.common.errors.TimeoutException) Test(org.junit.jupiter.api.Test)

Example 29 with Callback

use of org.apache.kafka.clients.producer.Callback in project kafka by apache.

the class ProducerBatchTest method testBatchAbort.

@Test
public void testBatchAbort() throws Exception {
    ProducerBatch batch = new ProducerBatch(new TopicPartition("topic", 1), memoryRecordsBuilder, now);
    MockCallback callback = new MockCallback();
    FutureRecordMetadata future = batch.tryAppend(now, null, new byte[10], Record.EMPTY_HEADERS, callback, now);
    KafkaException exception = new KafkaException();
    batch.abort(exception);
    assertTrue(future.isDone());
    assertEquals(1, callback.invocations);
    assertEquals(exception, callback.exception);
    assertNull(callback.metadata);
    // subsequent completion should be ignored
    assertFalse(batch.complete(500L, 2342342341L));
    assertFalse(batch.completeExceptionally(new KafkaException(), index -> new KafkaException()));
    assertEquals(1, callback.invocations);
    assertTrue(future.isDone());
    try {
        future.get();
        fail("Future should have thrown");
    } catch (ExecutionException e) {
        assertEquals(exception, e.getCause());
    }
}
Also used : Assertions.assertThrows(org.junit.jupiter.api.Assertions.assertThrows) Assertions.fail(org.junit.jupiter.api.Assertions.fail) Assertions.assertNotNull(org.junit.jupiter.api.Assertions.assertNotNull) Arrays(java.util.Arrays) MAGIC_VALUE_V2(org.apache.kafka.common.record.RecordBatch.MAGIC_VALUE_V2) MAGIC_VALUE_V1(org.apache.kafka.common.record.RecordBatch.MAGIC_VALUE_V1) Assertions.assertNull(org.junit.jupiter.api.Assertions.assertNull) KafkaException(org.apache.kafka.common.KafkaException) HashMap(java.util.HashMap) RecordHeader(org.apache.kafka.common.header.internals.RecordHeader) Deque(java.util.Deque) MAGIC_VALUE_V0(org.apache.kafka.common.record.RecordBatch.MAGIC_VALUE_V0) Function(java.util.function.Function) ByteBuffer(java.nio.ByteBuffer) Record(org.apache.kafka.common.record.Record) ArrayList(java.util.ArrayList) Assertions.assertFalse(org.junit.jupiter.api.Assertions.assertFalse) RecordBatch(org.apache.kafka.common.record.RecordBatch) Map(java.util.Map) Assertions.assertEquals(org.junit.jupiter.api.Assertions.assertEquals) TimestampType(org.apache.kafka.common.record.TimestampType) TopicPartition(org.apache.kafka.common.TopicPartition) MemoryRecordsBuilder(org.apache.kafka.common.record.MemoryRecordsBuilder) CompressionType(org.apache.kafka.common.record.CompressionType) TestUtils(org.apache.kafka.test.TestUtils) RecordMetadata(org.apache.kafka.clients.producer.RecordMetadata) Test(org.junit.jupiter.api.Test) ExecutionException(java.util.concurrent.ExecutionException) MemoryRecords(org.apache.kafka.common.record.MemoryRecords) List(java.util.List) Header(org.apache.kafka.common.header.Header) Assertions.assertTrue(org.junit.jupiter.api.Assertions.assertTrue) Callback(org.apache.kafka.clients.producer.Callback) TopicPartition(org.apache.kafka.common.TopicPartition) KafkaException(org.apache.kafka.common.KafkaException) ExecutionException(java.util.concurrent.ExecutionException) Test(org.junit.jupiter.api.Test)

Example 30 with Callback

use of org.apache.kafka.clients.producer.Callback in project kafka by apache.

the class ProducerPerformance method start.

void start(String[] args) throws IOException {
    ArgumentParser parser = argParser();
    try {
        Namespace res = parser.parseArgs(args);
        /* parse args */
        String topicName = res.getString("topic");
        long numRecords = res.getLong("numRecords");
        Integer recordSize = res.getInt("recordSize");
        int throughput = res.getInt("throughput");
        List<String> producerProps = res.getList("producerConfig");
        String producerConfig = res.getString("producerConfigFile");
        String payloadFilePath = res.getString("payloadFile");
        String transactionalId = res.getString("transactionalId");
        boolean shouldPrintMetrics = res.getBoolean("printMetrics");
        long transactionDurationMs = res.getLong("transactionDurationMs");
        boolean transactionsEnabled = 0 < transactionDurationMs;
        // since default value gets printed with the help text, we are escaping \n there and replacing it with correct value here.
        String payloadDelimiter = res.getString("payloadDelimiter").equals("\\n") ? "\n" : res.getString("payloadDelimiter");
        if (producerProps == null && producerConfig == null) {
            throw new ArgumentParserException("Either --producer-props or --producer.config must be specified.", parser);
        }
        List<byte[]> payloadByteList = readPayloadFile(payloadFilePath, payloadDelimiter);
        Properties props = readProps(producerProps, producerConfig, transactionalId, transactionsEnabled);
        KafkaProducer<byte[], byte[]> producer = createKafkaProducer(props);
        if (transactionsEnabled)
            producer.initTransactions();
        /* setup perf test */
        byte[] payload = null;
        if (recordSize != null) {
            payload = new byte[recordSize];
        }
        Random random = new Random(0);
        ProducerRecord<byte[], byte[]> record;
        Stats stats = new Stats(numRecords, 5000);
        long startMs = System.currentTimeMillis();
        ThroughputThrottler throttler = new ThroughputThrottler(throughput, startMs);
        int currentTransactionSize = 0;
        long transactionStartTime = 0;
        for (long i = 0; i < numRecords; i++) {
            payload = generateRandomPayload(recordSize, payloadByteList, payload, random);
            if (transactionsEnabled && currentTransactionSize == 0) {
                producer.beginTransaction();
                transactionStartTime = System.currentTimeMillis();
            }
            record = new ProducerRecord<>(topicName, payload);
            long sendStartMs = System.currentTimeMillis();
            Callback cb = stats.nextCompletion(sendStartMs, payload.length, stats);
            producer.send(record, cb);
            currentTransactionSize++;
            if (transactionsEnabled && transactionDurationMs <= (sendStartMs - transactionStartTime)) {
                producer.commitTransaction();
                currentTransactionSize = 0;
            }
            if (throttler.shouldThrottle(i, sendStartMs)) {
                throttler.throttle();
            }
        }
        if (transactionsEnabled && currentTransactionSize != 0)
            producer.commitTransaction();
        if (!shouldPrintMetrics) {
            producer.close();
            /* print final results */
            stats.printTotal();
        } else {
            // Make sure all messages are sent before printing out the stats and the metrics
            // We need to do this in a different branch for now since tests/kafkatest/sanity_checks/test_performance_services.py
            // expects this class to work with older versions of the client jar that don't support flush().
            producer.flush();
            /* print final results */
            stats.printTotal();
            /* print out metrics */
            ToolsUtils.printMetrics(producer.metrics());
            producer.close();
        }
    } catch (ArgumentParserException e) {
        if (args.length == 0) {
            parser.printHelp();
            Exit.exit(0);
        } else {
            parser.handleError(e);
            Exit.exit(1);
        }
    }
}
Also used : Properties(java.util.Properties) ArgumentParser(net.sourceforge.argparse4j.inf.ArgumentParser) Namespace(net.sourceforge.argparse4j.inf.Namespace) Callback(org.apache.kafka.clients.producer.Callback) Random(java.util.Random) ArgumentParserException(net.sourceforge.argparse4j.inf.ArgumentParserException)

Aggregations

Callback (org.apache.kafka.clients.producer.Callback)81 Test (org.junit.Test)47 ProducerRecord (org.apache.kafka.clients.producer.ProducerRecord)39 RecordMetadata (org.apache.kafka.clients.producer.RecordMetadata)37 KafkaException (org.apache.kafka.common.KafkaException)21 Future (java.util.concurrent.Future)18 TimeoutException (org.apache.kafka.common.errors.TimeoutException)18 ExecutionException (java.util.concurrent.ExecutionException)15 ArrayList (java.util.ArrayList)14 List (java.util.List)13 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)13 MockProducer (org.apache.kafka.clients.producer.MockProducer)13 HashMap (java.util.HashMap)12 Properties (java.util.Properties)12 DefaultPartitioner (org.apache.kafka.clients.producer.internals.DefaultPartitioner)12 TopicPartition (org.apache.kafka.common.TopicPartition)12 Schema (org.apache.kafka.connect.data.Schema)12 Struct (org.apache.kafka.connect.data.Struct)12 KafkaProducer (org.apache.kafka.clients.producer.KafkaProducer)11 StreamsException (org.apache.kafka.streams.errors.StreamsException)11