Search in sources :

Example 11 with ProduceRequest

use of org.apache.kafka.common.requests.ProduceRequest in project apache-kafka-on-k8s by banzaicloud.

the class SenderTest method testDownConversionForMismatchedMagicValues.

@Test
public void testDownConversionForMismatchedMagicValues() throws Exception {
    // it can happen that we construct a record set with mismatching magic values (perhaps
    // because the partition leader changed after the record set was initially constructed)
    // in this case, we down-convert record sets with newer magic values to match the oldest
    // created record set
    long offset = 0;
    // start off support produce request v3
    apiVersions.update("0", NodeApiVersions.create());
    Future<RecordMetadata> future1 = accumulator.append(tp0, 0L, "key".getBytes(), "value".getBytes(), null, null, MAX_BLOCK_TIMEOUT).future;
    // now the partition leader supports only v2
    apiVersions.update("0", NodeApiVersions.create(Collections.singleton(new ApiVersionsResponse.ApiVersion(ApiKeys.PRODUCE.id, (short) 0, (short) 2))));
    Future<RecordMetadata> future2 = accumulator.append(tp1, 0L, "key".getBytes(), "value".getBytes(), null, null, MAX_BLOCK_TIMEOUT).future;
    // start off support produce request v3
    apiVersions.update("0", NodeApiVersions.create());
    ProduceResponse.PartitionResponse resp = new ProduceResponse.PartitionResponse(Errors.NONE, offset, RecordBatch.NO_TIMESTAMP, 100);
    Map<TopicPartition, ProduceResponse.PartitionResponse> partResp = new HashMap<>();
    partResp.put(tp0, resp);
    partResp.put(tp1, resp);
    ProduceResponse produceResponse = new ProduceResponse(partResp, 0);
    client.prepareResponse(new MockClient.RequestMatcher() {

        @Override
        public boolean matches(AbstractRequest body) {
            ProduceRequest request = (ProduceRequest) body;
            if (request.version() != 2)
                return false;
            Map<TopicPartition, MemoryRecords> recordsMap = request.partitionRecordsOrFail();
            if (recordsMap.size() != 2)
                return false;
            for (MemoryRecords records : recordsMap.values()) {
                if (records == null || records.sizeInBytes() == 0 || !records.hasMatchingMagic(RecordBatch.MAGIC_VALUE_V1))
                    return false;
            }
            return true;
        }
    }, produceResponse);
    // connect
    sender.run(time.milliseconds());
    // send produce request
    sender.run(time.milliseconds());
    assertTrue("Request should be completed", future1.isDone());
    assertTrue("Request should be completed", future2.isDone());
}
Also used : ApiVersionsResponse(org.apache.kafka.common.requests.ApiVersionsResponse) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) ProduceRequest(org.apache.kafka.common.requests.ProduceRequest) ProduceResponse(org.apache.kafka.common.requests.ProduceResponse) AbstractRequest(org.apache.kafka.common.requests.AbstractRequest) RecordMetadata(org.apache.kafka.clients.producer.RecordMetadata) TopicPartition(org.apache.kafka.common.TopicPartition) Map(java.util.Map) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) MockClient(org.apache.kafka.clients.MockClient) MemoryRecords(org.apache.kafka.common.record.MemoryRecords) Test(org.junit.Test)

Example 12 with ProduceRequest

use of org.apache.kafka.common.requests.ProduceRequest in project apache-kafka-on-k8s by banzaicloud.

the class SenderTest method testClusterAuthorizationExceptionInProduceRequest.

@Test
public void testClusterAuthorizationExceptionInProduceRequest() throws Exception {
    final long producerId = 343434L;
    TransactionManager transactionManager = new TransactionManager();
    setupWithTransactionState(transactionManager);
    client.setNode(new Node(1, "localhost", 33343));
    prepareAndReceiveInitProducerId(producerId, Errors.NONE);
    assertTrue(transactionManager.hasProducerId());
    // cluster authorization is a fatal error for the producer
    Future<RecordMetadata> future = accumulator.append(tp0, time.milliseconds(), "key".getBytes(), "value".getBytes(), null, null, MAX_BLOCK_TIMEOUT).future;
    client.prepareResponse(new MockClient.RequestMatcher() {

        @Override
        public boolean matches(AbstractRequest body) {
            return body instanceof ProduceRequest && ((ProduceRequest) body).isIdempotent();
        }
    }, produceResponse(tp0, -1, Errors.CLUSTER_AUTHORIZATION_FAILED, 0));
    sender.run(time.milliseconds());
    assertFutureFailure(future, ClusterAuthorizationException.class);
    // cluster authorization errors are fatal, so we should continue seeing it on future sends
    assertTrue(transactionManager.hasFatalError());
    assertSendFailure(ClusterAuthorizationException.class);
}
Also used : RecordMetadata(org.apache.kafka.clients.producer.RecordMetadata) ProduceRequest(org.apache.kafka.common.requests.ProduceRequest) Node(org.apache.kafka.common.Node) AbstractRequest(org.apache.kafka.common.requests.AbstractRequest) MockClient(org.apache.kafka.clients.MockClient) Test(org.junit.Test)

Example 13 with ProduceRequest

use of org.apache.kafka.common.requests.ProduceRequest in project kafka by apache.

the class SenderTest method testDownConversionForMismatchedMagicValues.

@SuppressWarnings("deprecation")
@Test
public void testDownConversionForMismatchedMagicValues() throws Exception {
    // it can happen that we construct a record set with mismatching magic values (perhaps
    // because the partition leader changed after the record set was initially constructed)
    // in this case, we down-convert record sets with newer magic values to match the oldest
    // created record set
    long offset = 0;
    // start off support produce request v3
    apiVersions.update("0", NodeApiVersions.create());
    Future<RecordMetadata> future1 = appendToAccumulator(tp0, 0L, "key", "value");
    // now the partition leader supports only v2
    apiVersions.update("0", NodeApiVersions.create(ApiKeys.PRODUCE.id, (short) 0, (short) 2));
    Future<RecordMetadata> future2 = appendToAccumulator(tp1, 0L, "key", "value");
    // start off support produce request v3
    apiVersions.update("0", NodeApiVersions.create());
    ProduceResponse.PartitionResponse resp = new ProduceResponse.PartitionResponse(Errors.NONE, offset, RecordBatch.NO_TIMESTAMP, 100);
    Map<TopicPartition, ProduceResponse.PartitionResponse> partResp = new HashMap<>();
    partResp.put(tp0, resp);
    partResp.put(tp1, resp);
    ProduceResponse produceResponse = new ProduceResponse(partResp, 0);
    client.prepareResponse(body -> {
        ProduceRequest request = (ProduceRequest) body;
        if (request.version() != 2)
            return false;
        Map<TopicPartition, MemoryRecords> recordsMap = partitionRecords(request);
        if (recordsMap.size() != 2)
            return false;
        for (MemoryRecords records : recordsMap.values()) {
            if (records == null || records.sizeInBytes() == 0 || !records.hasMatchingMagic(RecordBatch.MAGIC_VALUE_V1))
                return false;
        }
        return true;
    }, produceResponse);
    // connect
    sender.runOnce();
    // send produce request
    sender.runOnce();
    assertTrue(future1.isDone(), "Request should be completed");
    assertTrue(future2.isDone(), "Request should be completed");
}
Also used : RecordMetadata(org.apache.kafka.clients.producer.RecordMetadata) LinkedHashMap(java.util.LinkedHashMap) IdentityHashMap(java.util.IdentityHashMap) HashMap(java.util.HashMap) ProduceRequest(org.apache.kafka.common.requests.ProduceRequest) ProduceResponse(org.apache.kafka.common.requests.ProduceResponse) TopicPartition(org.apache.kafka.common.TopicPartition) MemoryRecords(org.apache.kafka.common.record.MemoryRecords) Test(org.junit.jupiter.api.Test)

Example 14 with ProduceRequest

use of org.apache.kafka.common.requests.ProduceRequest in project kafka by apache.

the class SenderTest method partitionRecords.

private static Map<TopicPartition, MemoryRecords> partitionRecords(ProduceRequest request) {
    Map<TopicPartition, MemoryRecords> partitionRecords = new HashMap<>();
    request.data().topicData().forEach(tpData -> tpData.partitionData().forEach(p -> {
        TopicPartition tp = new TopicPartition(tpData.name(), p.index());
        partitionRecords.put(tp, (MemoryRecords) p.records());
    }));
    return Collections.unmodifiableMap(partitionRecords);
}
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) LinkedHashMap(java.util.LinkedHashMap) IdentityHashMap(java.util.IdentityHashMap) HashMap(java.util.HashMap) TopicPartition(org.apache.kafka.common.TopicPartition) MemoryRecords(org.apache.kafka.common.record.MemoryRecords)

Example 15 with ProduceRequest

use of org.apache.kafka.common.requests.ProduceRequest in project kafka by apache.

the class SenderTest method sendIdempotentProducerResponse.

void sendIdempotentProducerResponse(int expectedEpoch, int expectedSequence, TopicPartition tp, Errors responseError, long responseOffset, long logStartOffset) {
    client.respond(body -> {
        ProduceRequest produceRequest = (ProduceRequest) body;
        assertTrue(RequestTestUtils.hasIdempotentRecords(produceRequest));
        MemoryRecords records = partitionRecords(produceRequest).get(tp);
        Iterator<MutableRecordBatch> batchIterator = records.batches().iterator();
        RecordBatch firstBatch = batchIterator.next();
        assertFalse(batchIterator.hasNext());
        if (expectedEpoch > -1)
            assertEquals((short) expectedEpoch, firstBatch.producerEpoch());
        assertEquals(expectedSequence, firstBatch.baseSequence());
        return true;
    }, produceResponse(tp, responseOffset, responseError, 0, logStartOffset, null));
}
Also used : MutableRecordBatch(org.apache.kafka.common.record.MutableRecordBatch) ProduceRequest(org.apache.kafka.common.requests.ProduceRequest) RecordBatch(org.apache.kafka.common.record.RecordBatch) MutableRecordBatch(org.apache.kafka.common.record.MutableRecordBatch) MemoryRecords(org.apache.kafka.common.record.MemoryRecords)

Aggregations

ProduceRequest (org.apache.kafka.common.requests.ProduceRequest)15 RecordMetadata (org.apache.kafka.clients.producer.RecordMetadata)12 AbstractRequest (org.apache.kafka.common.requests.AbstractRequest)10 MemoryRecords (org.apache.kafka.common.record.MemoryRecords)9 MockClient (org.apache.kafka.clients.MockClient)8 Node (org.apache.kafka.common.Node)8 Test (org.junit.Test)7 MutableRecordBatch (org.apache.kafka.common.record.MutableRecordBatch)6 Test (org.junit.jupiter.api.Test)5 TopicPartition (org.apache.kafka.common.TopicPartition)4 RecordBatch (org.apache.kafka.common.record.RecordBatch)4 HashMap (java.util.HashMap)3 LinkedHashMap (java.util.LinkedHashMap)3 ExecutionException (java.util.concurrent.ExecutionException)3 ClusterAuthorizationException (org.apache.kafka.common.errors.ClusterAuthorizationException)3 NetworkException (org.apache.kafka.common.errors.NetworkException)3 RecordTooLargeException (org.apache.kafka.common.errors.RecordTooLargeException)3 TimeoutException (org.apache.kafka.common.errors.TimeoutException)3 TopicAuthorizationException (org.apache.kafka.common.errors.TopicAuthorizationException)3 UnsupportedForMessageFormatException (org.apache.kafka.common.errors.UnsupportedForMessageFormatException)3