Search in sources :

Example 6 with RequestHeader

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

the class NetworkClientTest method testAuthenticationFailureWithInFlightMetadataRequest.

@Test
public void testAuthenticationFailureWithInFlightMetadataRequest() {
    int refreshBackoffMs = 50;
    MetadataResponse metadataResponse = RequestTestUtils.metadataUpdateWith(2, Collections.emptyMap());
    Metadata metadata = new Metadata(refreshBackoffMs, 5000, new LogContext(), new ClusterResourceListeners());
    metadata.updateWithCurrentRequestVersion(metadataResponse, false, time.milliseconds());
    Cluster cluster = metadata.fetch();
    Node node1 = cluster.nodes().get(0);
    Node node2 = cluster.nodes().get(1);
    NetworkClient client = createNetworkClientWithNoVersionDiscovery(metadata);
    awaitReady(client, node1);
    metadata.requestUpdate();
    time.sleep(refreshBackoffMs);
    client.poll(0, time.milliseconds());
    Optional<Node> nodeWithPendingMetadataOpt = cluster.nodes().stream().filter(node -> client.hasInFlightRequests(node.idString())).findFirst();
    assertEquals(Optional.of(node1), nodeWithPendingMetadataOpt);
    assertFalse(client.ready(node2, time.milliseconds()));
    selector.serverAuthenticationFailed(node2.idString());
    client.poll(0, time.milliseconds());
    assertNotNull(client.authenticationException(node2));
    ByteBuffer requestBuffer = selector.completedSendBuffers().get(0).buffer();
    RequestHeader header = parseHeader(requestBuffer);
    assertEquals(ApiKeys.METADATA, header.apiKey());
    ByteBuffer responseBuffer = RequestTestUtils.serializeResponseWithHeader(metadataResponse, header.apiVersion(), header.correlationId());
    selector.delayedReceive(new DelayedReceive(node1.idString(), new NetworkReceive(node1.idString(), responseBuffer)));
    int initialUpdateVersion = metadata.updateVersion();
    client.poll(0, time.milliseconds());
    assertEquals(initialUpdateVersion + 1, metadata.updateVersion());
}
Also used : BeforeEach(org.junit.jupiter.api.BeforeEach) MockTime(org.apache.kafka.common.utils.MockTime) Arrays(java.util.Arrays) ProduceRequest(org.apache.kafka.common.requests.ProduceRequest) Assertions.assertNotEquals(org.junit.jupiter.api.Assertions.assertNotEquals) KafkaException(org.apache.kafka.common.KafkaException) ByteBuffer(java.nio.ByteBuffer) InetAddress(java.net.InetAddress) Cluster(org.apache.kafka.common.Cluster) RequestHeader(org.apache.kafka.common.requests.RequestHeader) Assertions.assertFalse(org.junit.jupiter.api.Assertions.assertFalse) SaslClientAuthenticator(org.apache.kafka.common.security.authenticator.SaslClientAuthenticator) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ApiVersionsResponse(org.apache.kafka.common.requests.ApiVersionsResponse) LogContext(org.apache.kafka.common.utils.LogContext) ApiVersionsResponseData(org.apache.kafka.common.message.ApiVersionsResponseData) ProduceResponseData(org.apache.kafka.common.message.ProduceResponseData) TestUtils(org.apache.kafka.test.TestUtils) PRODUCE(org.apache.kafka.common.protocol.ApiKeys.PRODUCE) ApiVersionCollection(org.apache.kafka.common.message.ApiVersionsResponseData.ApiVersionCollection) Set(java.util.Set) ClusterResourceListeners(org.apache.kafka.common.internals.ClusterResourceListeners) Collectors(java.util.stream.Collectors) Test(org.junit.jupiter.api.Test) List(java.util.List) ApiMessageType(org.apache.kafka.common.message.ApiMessageType) Assertions.assertTrue(org.junit.jupiter.api.Assertions.assertTrue) Errors(org.apache.kafka.common.protocol.Errors) Optional(java.util.Optional) Node(org.apache.kafka.common.Node) MetadataResponse(org.apache.kafka.common.requests.MetadataResponse) AuthenticationException(org.apache.kafka.common.errors.AuthenticationException) IntStream(java.util.stream.IntStream) Assertions.assertThrows(org.junit.jupiter.api.Assertions.assertThrows) Assertions.fail(org.junit.jupiter.api.Assertions.fail) Assertions.assertNotNull(org.junit.jupiter.api.Assertions.assertNotNull) AbstractResponse(org.apache.kafka.common.requests.AbstractResponse) Assertions.assertNull(org.junit.jupiter.api.Assertions.assertNull) RequestTestUtils(org.apache.kafka.common.requests.RequestTestUtils) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) MetadataRequest(org.apache.kafka.common.requests.MetadataRequest) ApiVersion(org.apache.kafka.common.message.ApiVersionsResponseData.ApiVersion) Assertions.assertEquals(org.junit.jupiter.api.Assertions.assertEquals) ProduceRequestData(org.apache.kafka.common.message.ProduceRequestData) ProduceResponse(org.apache.kafka.common.requests.ProduceResponse) MockSelector(org.apache.kafka.test.MockSelector) ApiKeys(org.apache.kafka.common.protocol.ApiKeys) UnknownHostException(java.net.UnknownHostException) NetworkReceive(org.apache.kafka.common.network.NetworkReceive) DelayedReceive(org.apache.kafka.test.DelayedReceive) UnsupportedVersionException(org.apache.kafka.common.errors.UnsupportedVersionException) Collections(java.util.Collections) ClusterResourceListeners(org.apache.kafka.common.internals.ClusterResourceListeners) Node(org.apache.kafka.common.Node) NetworkReceive(org.apache.kafka.common.network.NetworkReceive) LogContext(org.apache.kafka.common.utils.LogContext) Cluster(org.apache.kafka.common.Cluster) ByteBuffer(java.nio.ByteBuffer) MetadataResponse(org.apache.kafka.common.requests.MetadataResponse) RequestHeader(org.apache.kafka.common.requests.RequestHeader) DelayedReceive(org.apache.kafka.test.DelayedReceive) Test(org.junit.jupiter.api.Test)

Example 7 with RequestHeader

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

the class NetworkClient method doSend.

private void doSend(ClientRequest clientRequest, boolean isInternalRequest, long now, AbstractRequest request) {
    String destination = clientRequest.destination();
    RequestHeader header = clientRequest.makeHeader(request.version());
    if (log.isDebugEnabled()) {
        log.debug("Sending {} request with header {} and timeout {} to node {}: {}", clientRequest.apiKey(), header, clientRequest.requestTimeoutMs(), destination, request);
    }
    Send send = request.toSend(header);
    InFlightRequest inFlightRequest = new InFlightRequest(clientRequest, header, isInternalRequest, request, send, now);
    this.inFlightRequests.add(inFlightRequest);
    selector.send(new NetworkSend(clientRequest.destination(), send));
}
Also used : RequestHeader(org.apache.kafka.common.requests.RequestHeader) NetworkSend(org.apache.kafka.common.network.NetworkSend) Send(org.apache.kafka.common.network.Send) NetworkSend(org.apache.kafka.common.network.NetworkSend)

Example 8 with RequestHeader

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

the class Sender method handleProduceResponse.

/**
 * Handle a produce response
 */
private void handleProduceResponse(ClientResponse response, Map<TopicPartition, ProducerBatch> batches, long now) {
    RequestHeader requestHeader = response.requestHeader();
    int correlationId = requestHeader.correlationId();
    if (response.wasDisconnected()) {
        log.trace("Cancelled request with header {} due to node {} being disconnected", requestHeader, response.destination());
        for (ProducerBatch batch : batches.values()) completeBatch(batch, new ProduceResponse.PartitionResponse(Errors.NETWORK_EXCEPTION, String.format("Disconnected from node %s", response.destination())), correlationId, now);
    } else if (response.versionMismatch() != null) {
        log.warn("Cancelled request {} due to a version mismatch with node {}", response, response.destination(), response.versionMismatch());
        for (ProducerBatch batch : batches.values()) completeBatch(batch, new ProduceResponse.PartitionResponse(Errors.UNSUPPORTED_VERSION), correlationId, now);
    } else {
        log.trace("Received produce response from node {} with correlation id {}", response.destination(), correlationId);
        // if we have a response, parse it
        if (response.hasResponse()) {
            // Sender should exercise PartitionProduceResponse rather than ProduceResponse.PartitionResponse
            // https://issues.apache.org/jira/browse/KAFKA-10696
            ProduceResponse produceResponse = (ProduceResponse) response.responseBody();
            produceResponse.data().responses().forEach(r -> r.partitionResponses().forEach(p -> {
                TopicPartition tp = new TopicPartition(r.name(), p.index());
                ProduceResponse.PartitionResponse partResp = new ProduceResponse.PartitionResponse(Errors.forCode(p.errorCode()), p.baseOffset(), p.logAppendTimeMs(), p.logStartOffset(), p.recordErrors().stream().map(e -> new ProduceResponse.RecordError(e.batchIndex(), e.batchIndexErrorMessage())).collect(Collectors.toList()), p.errorMessage());
                ProducerBatch batch = batches.get(tp);
                completeBatch(batch, partResp, correlationId, now);
            }));
            this.sensors.recordLatency(response.destination(), response.requestLatencyMs());
        } else {
            // this is the acks = 0 case, just complete all requests
            for (ProducerBatch batch : batches.values()) {
                completeBatch(batch, new ProduceResponse.PartitionResponse(Errors.NONE), correlationId, now);
            }
        }
    }
}
Also used : Max(org.apache.kafka.common.metrics.stats.Max) TransactionAbortedException(org.apache.kafka.common.errors.TransactionAbortedException) ProduceRequest(org.apache.kafka.common.requests.ProduceRequest) Metadata(org.apache.kafka.clients.Metadata) KafkaException(org.apache.kafka.common.KafkaException) HashMap(java.util.HashMap) RetriableException(org.apache.kafka.common.errors.RetriableException) AbstractRequest(org.apache.kafka.common.requests.AbstractRequest) ClusterAuthorizationException(org.apache.kafka.common.errors.ClusterAuthorizationException) Function(java.util.function.Function) ClientRequest(org.apache.kafka.clients.ClientRequest) InvalidRecordException(org.apache.kafka.common.InvalidRecordException) ArrayList(java.util.ArrayList) Cluster(org.apache.kafka.common.Cluster) RequestHeader(org.apache.kafka.common.requests.RequestHeader) FindCoordinatorRequest(org.apache.kafka.common.requests.FindCoordinatorRequest) InvalidMetadataException(org.apache.kafka.common.errors.InvalidMetadataException) KafkaClient(org.apache.kafka.clients.KafkaClient) RecordBatch(org.apache.kafka.common.record.RecordBatch) LogContext(org.apache.kafka.common.utils.LogContext) Map(java.util.Map) MetricName(org.apache.kafka.common.MetricName) ProduceRequestData(org.apache.kafka.common.message.ProduceRequestData) ProduceResponse(org.apache.kafka.common.requests.ProduceResponse) TopicPartition(org.apache.kafka.common.TopicPartition) Sensor(org.apache.kafka.common.metrics.Sensor) TimeoutException(org.apache.kafka.common.errors.TimeoutException) Logger(org.slf4j.Logger) Time(org.apache.kafka.common.utils.Time) Iterator(java.util.Iterator) IOException(java.io.IOException) ApiVersions(org.apache.kafka.clients.ApiVersions) Collectors(java.util.stream.Collectors) Objects(java.util.Objects) MemoryRecords(org.apache.kafka.common.record.MemoryRecords) List(java.util.List) NetworkClientUtils(org.apache.kafka.clients.NetworkClientUtils) RequestCompletionHandler(org.apache.kafka.clients.RequestCompletionHandler) Avg(org.apache.kafka.common.metrics.stats.Avg) TopicAuthorizationException(org.apache.kafka.common.errors.TopicAuthorizationException) Errors(org.apache.kafka.common.protocol.Errors) Node(org.apache.kafka.common.Node) UnknownTopicOrPartitionException(org.apache.kafka.common.errors.UnknownTopicOrPartitionException) Meter(org.apache.kafka.common.metrics.stats.Meter) Collections(java.util.Collections) ClientResponse(org.apache.kafka.clients.ClientResponse) AuthenticationException(org.apache.kafka.common.errors.AuthenticationException) ProduceResponse(org.apache.kafka.common.requests.ProduceResponse) TopicPartition(org.apache.kafka.common.TopicPartition) RequestHeader(org.apache.kafka.common.requests.RequestHeader)

Example 9 with RequestHeader

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

the class SaslAuthenticatorTest method testInvalidApiVersionsRequest.

/**
 * Tests that invalid ApiVersionRequest is handled by the server correctly and
 * returns an INVALID_REQUEST error.
 */
@Test
public void testInvalidApiVersionsRequest() throws Exception {
    short handshakeVersion = ApiKeys.SASL_HANDSHAKE.latestVersion();
    SecurityProtocol securityProtocol = SecurityProtocol.SASL_PLAINTEXT;
    configureMechanisms("PLAIN", Arrays.asList("PLAIN"));
    server = createEchoServer(securityProtocol);
    // Send ApiVersionsRequest with invalid version and validate error response.
    String node = "1";
    short version = ApiKeys.API_VERSIONS.latestVersion();
    createClientConnection(SecurityProtocol.PLAINTEXT, node);
    RequestHeader header = new RequestHeader(ApiKeys.API_VERSIONS, version, "someclient", 1);
    ApiVersionsRequest request = new ApiVersionsRequest(new ApiVersionsRequestData().setClientSoftwareName("  ").setClientSoftwareVersion("   "), version);
    selector.send(new NetworkSend(node, request.toSend(header)));
    ByteBuffer responseBuffer = waitForResponse();
    ResponseHeader.parse(responseBuffer, ApiKeys.API_VERSIONS.responseHeaderVersion(version));
    ApiVersionsResponse response = ApiVersionsResponse.parse(responseBuffer, version);
    assertEquals(Errors.INVALID_REQUEST.code(), response.data().errorCode());
    // Send ApiVersionsRequest with a supported version. This should succeed.
    sendVersionRequestReceiveResponse(node);
    // Test that client can authenticate successfully
    sendHandshakeRequestReceiveResponse(node, handshakeVersion);
    authenticateUsingSaslPlainAndCheckConnection(node, handshakeVersion > 0);
}
Also used : ApiVersionsResponse(org.apache.kafka.common.requests.ApiVersionsResponse) SecurityProtocol(org.apache.kafka.common.security.auth.SecurityProtocol) RequestHeader(org.apache.kafka.common.requests.RequestHeader) NetworkSend(org.apache.kafka.common.network.NetworkSend) ApiVersionsRequest(org.apache.kafka.common.requests.ApiVersionsRequest) ApiVersionsRequestData(org.apache.kafka.common.message.ApiVersionsRequestData) ByteBuffer(java.nio.ByteBuffer) Test(org.junit.jupiter.api.Test)

Example 10 with RequestHeader

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

the class SaslAuthenticatorTest method testConvertListOffsetResponseToSaslHandshakeResponse.

@Test
public void testConvertListOffsetResponseToSaslHandshakeResponse() {
    ListOffsetsResponseData data = new ListOffsetsResponseData().setThrottleTimeMs(0).setTopics(Collections.singletonList(new ListOffsetsTopicResponse().setName("topic").setPartitions(Collections.singletonList(new ListOffsetsPartitionResponse().setErrorCode(Errors.NONE.code()).setLeaderEpoch(ListOffsetsResponse.UNKNOWN_EPOCH).setPartitionIndex(0).setOffset(0).setTimestamp(0)))));
    ListOffsetsResponse response = new ListOffsetsResponse(data);
    ByteBuffer buffer = RequestTestUtils.serializeResponseWithHeader(response, LIST_OFFSETS.latestVersion(), 0);
    final RequestHeader header0 = new RequestHeader(LIST_OFFSETS, LIST_OFFSETS.latestVersion(), "id", SaslClientAuthenticator.MIN_RESERVED_CORRELATION_ID);
    assertThrows(SchemaException.class, () -> NetworkClient.parseResponse(buffer.duplicate(), header0));
    final RequestHeader header1 = new RequestHeader(LIST_OFFSETS, LIST_OFFSETS.latestVersion(), "id", 1);
    assertThrows(IllegalStateException.class, () -> NetworkClient.parseResponse(buffer.duplicate(), header1));
}
Also used : ListOffsetsTopicResponse(org.apache.kafka.common.message.ListOffsetsResponseData.ListOffsetsTopicResponse) ListOffsetsPartitionResponse(org.apache.kafka.common.message.ListOffsetsResponseData.ListOffsetsPartitionResponse) RequestHeader(org.apache.kafka.common.requests.RequestHeader) ListOffsetsResponse(org.apache.kafka.common.requests.ListOffsetsResponse) ListOffsetsResponseData(org.apache.kafka.common.message.ListOffsetsResponseData) ByteBuffer(java.nio.ByteBuffer) Test(org.junit.jupiter.api.Test)

Aggregations

RequestHeader (org.apache.kafka.common.requests.RequestHeader)35 ByteBuffer (java.nio.ByteBuffer)19 SecurityProtocol (org.apache.kafka.common.security.auth.SecurityProtocol)12 Test (org.junit.jupiter.api.Test)12 ApiVersionsRequest (org.apache.kafka.common.requests.ApiVersionsRequest)11 NetworkSend (org.apache.kafka.common.network.NetworkSend)10 ApiVersionsResponse (org.apache.kafka.common.requests.ApiVersionsResponse)10 ApiKeys (org.apache.kafka.common.protocol.ApiKeys)7 IllegalSaslStateException (org.apache.kafka.common.errors.IllegalSaslStateException)6 RequestContext (org.apache.kafka.common.requests.RequestContext)6 Test (org.junit.Test)5 Collections (java.util.Collections)4 MetadataRequest (org.apache.kafka.common.requests.MetadataRequest)4 IOException (java.io.IOException)3 InetAddress (java.net.InetAddress)3 HashMap (java.util.HashMap)3 Map (java.util.Map)3 ApiVersionsResponseData (org.apache.kafka.common.message.ApiVersionsResponseData)3 ApiVersion (org.apache.kafka.common.message.ApiVersionsResponseData.ApiVersion)3 TransportLayer (org.apache.kafka.common.network.TransportLayer)3