Search in sources :

Example 1 with ConsumerMetadata

use of org.apache.kafka.clients.consumer.internals.ConsumerMetadata in project kafka by apache.

the class KafkaConsumerTest method testGetGroupMetadata.

@Test
public void testGetGroupMetadata() {
    final ConsumerMetadata metadata = createMetadata(subscription);
    final MockClient client = new MockClient(time, metadata);
    initMetadata(client, Collections.singletonMap(topic, 1));
    final Node node = metadata.fetch().nodes().get(0);
    final KafkaConsumer<String, String> consumer = newConsumer(time, client, subscription, metadata, assignor, true, groupInstanceId);
    final ConsumerGroupMetadata groupMetadataOnStart = consumer.groupMetadata();
    assertEquals(groupId, groupMetadataOnStart.groupId());
    assertEquals(JoinGroupRequest.UNKNOWN_MEMBER_ID, groupMetadataOnStart.memberId());
    assertEquals(JoinGroupRequest.UNKNOWN_GENERATION_ID, groupMetadataOnStart.generationId());
    assertEquals(groupInstanceId, groupMetadataOnStart.groupInstanceId());
    consumer.subscribe(singleton(topic), getConsumerRebalanceListener(consumer));
    prepareRebalance(client, node, assignor, singletonList(tp0), null);
    // initial fetch
    client.prepareResponseFrom(fetchResponse(tp0, 0, 0), node);
    consumer.updateAssignmentMetadataIfNeeded(time.timer(Long.MAX_VALUE));
    final ConsumerGroupMetadata groupMetadataAfterPoll = consumer.groupMetadata();
    assertEquals(groupId, groupMetadataAfterPoll.groupId());
    assertEquals(memberId, groupMetadataAfterPoll.memberId());
    assertEquals(1, groupMetadataAfterPoll.generationId());
    assertEquals(groupInstanceId, groupMetadataAfterPoll.groupInstanceId());
}
Also used : ConsumerMetadata(org.apache.kafka.clients.consumer.internals.ConsumerMetadata) Node(org.apache.kafka.common.Node) MockClient(org.apache.kafka.clients.MockClient) Test(org.junit.jupiter.api.Test)

Example 2 with ConsumerMetadata

use of org.apache.kafka.clients.consumer.internals.ConsumerMetadata in project kafka by apache.

the class KafkaConsumerTest method testUnsubscribeShouldTriggerPartitionsLostWithNoGeneration.

@Test
public void testUnsubscribeShouldTriggerPartitionsLostWithNoGeneration() throws Exception {
    ConsumerMetadata metadata = createMetadata(subscription);
    MockClient client = new MockClient(time, metadata);
    initMetadata(client, Collections.singletonMap(topic, 1));
    Node node = metadata.fetch().nodes().get(0);
    CooperativeStickyAssignor assignor = new CooperativeStickyAssignor();
    KafkaConsumer<String, String> consumer = newConsumer(time, client, subscription, metadata, assignor, false, groupInstanceId);
    initializeSubscriptionWithSingleTopic(consumer, getExceptionConsumerRebalanceListener());
    Node coordinator = prepareRebalance(client, node, assignor, singletonList(tp0), null);
    RuntimeException assignException = assertThrows(RuntimeException.class, () -> consumer.updateAssignmentMetadataIfNeeded(time.timer(Long.MAX_VALUE)));
    assertEquals(partitionAssigned + singleTopicPartition, assignException.getCause().getMessage());
    AtomicBoolean heartbeatReceived = prepareHeartbeatResponse(client, coordinator, Errors.UNKNOWN_MEMBER_ID);
    time.sleep(heartbeatIntervalMs);
    TestUtils.waitForCondition(heartbeatReceived::get, "Heartbeat response did not occur within timeout.");
    RuntimeException unsubscribeException = assertThrows(RuntimeException.class, consumer::unsubscribe);
    assertEquals(partitionLost + singleTopicPartition, unsubscribeException.getCause().getMessage());
}
Also used : ConsumerMetadata(org.apache.kafka.clients.consumer.internals.ConsumerMetadata) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Node(org.apache.kafka.common.Node) MockClient(org.apache.kafka.clients.MockClient) Test(org.junit.jupiter.api.Test)

Example 3 with ConsumerMetadata

use of org.apache.kafka.clients.consumer.internals.ConsumerMetadata in project kafka by apache.

the class KafkaConsumerTest method testShouldAttemptToRejoinGroupAfterSyncGroupFailed.

@Test
public void testShouldAttemptToRejoinGroupAfterSyncGroupFailed() throws Exception {
    ConsumerMetadata metadata = createMetadata(subscription);
    MockClient client = new MockClient(time, metadata);
    initMetadata(client, Collections.singletonMap(topic, 1));
    Node node = metadata.fetch().nodes().get(0);
    KafkaConsumer<String, String> consumer = newConsumer(time, client, subscription, metadata, assignor, false, groupInstanceId);
    consumer.subscribe(singleton(topic), getConsumerRebalanceListener(consumer));
    client.prepareResponseFrom(FindCoordinatorResponse.prepareResponse(Errors.NONE, groupId, node), node);
    Node coordinator = new Node(Integer.MAX_VALUE - node.id(), node.host(), node.port());
    client.prepareResponseFrom(joinGroupFollowerResponse(assignor, 1, memberId, leaderId, Errors.NONE), coordinator);
    client.prepareResponseFrom(syncGroupResponse(singletonList(tp0), Errors.NONE), coordinator);
    client.prepareResponseFrom(fetchResponse(tp0, 0, 1), node);
    client.prepareResponseFrom(fetchResponse(tp0, 1, 0), node);
    consumer.updateAssignmentMetadataIfNeeded(time.timer(Long.MAX_VALUE));
    consumer.poll(Duration.ZERO);
    // heartbeat fails due to rebalance in progress
    client.prepareResponseFrom(body -> true, new HeartbeatResponse(new HeartbeatResponseData().setErrorCode(Errors.REBALANCE_IN_PROGRESS.code())), coordinator);
    // join group
    final ByteBuffer byteBuffer = ConsumerProtocol.serializeSubscription(new ConsumerPartitionAssignor.Subscription(singletonList(topic)));
    // This member becomes the leader
    final JoinGroupResponse leaderResponse = new JoinGroupResponse(new JoinGroupResponseData().setErrorCode(Errors.NONE.code()).setGenerationId(1).setProtocolName(assignor.name()).setLeader(memberId).setMemberId(memberId).setMembers(Collections.singletonList(new JoinGroupResponseData.JoinGroupResponseMember().setMemberId(memberId).setMetadata(byteBuffer.array()))));
    client.prepareResponseFrom(leaderResponse, coordinator);
    // sync group fails due to disconnect
    client.prepareResponseFrom(syncGroupResponse(singletonList(tp0), Errors.NONE), coordinator, true);
    // should try and find the new coordinator
    client.prepareResponseFrom(FindCoordinatorResponse.prepareResponse(Errors.NONE, groupId, node), node);
    // rejoin group
    client.prepareResponseFrom(joinGroupFollowerResponse(assignor, 1, memberId, leaderId, Errors.NONE), coordinator);
    client.prepareResponseFrom(syncGroupResponse(singletonList(tp0), Errors.NONE), coordinator);
    client.prepareResponseFrom(body -> body instanceof FetchRequest && ((FetchRequest) body).fetchData(topicNames).containsKey(new TopicIdPartition(topicId, tp0)), fetchResponse(tp0, 1, 1), node);
    time.sleep(heartbeatIntervalMs);
    Thread.sleep(heartbeatIntervalMs);
    consumer.updateAssignmentMetadataIfNeeded(time.timer(Long.MAX_VALUE));
    final ConsumerRecords<String, String> records = consumer.poll(Duration.ZERO);
    assertFalse(records.isEmpty());
    consumer.close(Duration.ofMillis(0));
}
Also used : ConsumerMetadata(org.apache.kafka.clients.consumer.internals.ConsumerMetadata) HeartbeatResponse(org.apache.kafka.common.requests.HeartbeatResponse) JoinGroupResponse(org.apache.kafka.common.requests.JoinGroupResponse) JoinGroupResponseData(org.apache.kafka.common.message.JoinGroupResponseData) Node(org.apache.kafka.common.Node) TopicIdPartition(org.apache.kafka.common.TopicIdPartition) ByteBuffer(java.nio.ByteBuffer) FetchRequest(org.apache.kafka.common.requests.FetchRequest) HeartbeatResponseData(org.apache.kafka.common.message.HeartbeatResponseData) MockClient(org.apache.kafka.clients.MockClient) Test(org.junit.jupiter.api.Test)

Example 4 with ConsumerMetadata

use of org.apache.kafka.clients.consumer.internals.ConsumerMetadata in project kafka by apache.

the class KafkaConsumerTest method testMeasureCommittedDuration.

@Test
public void testMeasureCommittedDuration() {
    long offset1 = 10000;
    Time time = new MockTime(Duration.ofSeconds(1).toMillis());
    SubscriptionState subscription = new SubscriptionState(new LogContext(), OffsetResetStrategy.EARLIEST);
    ConsumerMetadata metadata = createMetadata(subscription);
    MockClient client = new MockClient(time, metadata);
    initMetadata(client, Collections.singletonMap(topic, 2));
    Node node = metadata.fetch().nodes().get(0);
    KafkaConsumer<String, String> consumer = newConsumer(time, client, subscription, metadata, assignor, true, groupInstanceId);
    consumer.assign(singletonList(tp0));
    // lookup coordinator
    client.prepareResponseFrom(FindCoordinatorResponse.prepareResponse(Errors.NONE, groupId, node), node);
    Node coordinator = new Node(Integer.MAX_VALUE - node.id(), node.host(), node.port());
    // fetch offset for one topic
    client.prepareResponseFrom(offsetResponse(Collections.singletonMap(tp0, offset1), Errors.NONE), coordinator);
    consumer.committed(Collections.singleton(tp0)).get(tp0).offset();
    final Metric metric = consumer.metrics().get(consumer.metrics.metricName("committed-time-ns-total", "consumer-metrics"));
    assertTrue((Double) metric.metricValue() >= Duration.ofMillis(999).toNanos());
}
Also used : ConsumerMetadata(org.apache.kafka.clients.consumer.internals.ConsumerMetadata) SubscriptionState(org.apache.kafka.clients.consumer.internals.SubscriptionState) Node(org.apache.kafka.common.Node) LogContext(org.apache.kafka.common.utils.LogContext) MockTime(org.apache.kafka.common.utils.MockTime) Time(org.apache.kafka.common.utils.Time) Metric(org.apache.kafka.common.Metric) MockTime(org.apache.kafka.common.utils.MockTime) MockClient(org.apache.kafka.clients.MockClient) Test(org.junit.jupiter.api.Test)

Example 5 with ConsumerMetadata

use of org.apache.kafka.clients.consumer.internals.ConsumerMetadata in project kafka by apache.

the class KafkaConsumerTest method testCurrentLag.

@Test
public void testCurrentLag() {
    final ConsumerMetadata metadata = createMetadata(subscription);
    final MockClient client = new MockClient(time, metadata);
    initMetadata(client, singletonMap(topic, 1));
    final KafkaConsumer<String, String> consumer = newConsumer(time, client, subscription, metadata, assignor, true, groupInstanceId);
    // throws for unassigned partition
    assertThrows(IllegalStateException.class, () -> consumer.currentLag(tp0));
    consumer.assign(singleton(tp0));
    // poll once to update with the current metadata
    consumer.poll(Duration.ofMillis(0));
    client.respond(FindCoordinatorResponse.prepareResponse(Errors.NONE, groupId, metadata.fetch().nodes().get(0)));
    // no error for no current position
    assertEquals(OptionalLong.empty(), consumer.currentLag(tp0));
    assertEquals(0, client.inFlightRequestCount());
    // poll once again, which should send the list-offset request
    consumer.seek(tp0, 50L);
    consumer.poll(Duration.ofMillis(0));
    // requests: list-offset, fetch
    assertEquals(2, client.inFlightRequestCount());
    // no error for no end offset (so unknown lag)
    assertEquals(OptionalLong.empty(), consumer.currentLag(tp0));
    // poll once again, which should return the list-offset response
    // and hence next call would return correct lag result
    client.respond(listOffsetsResponse(singletonMap(tp0, 90L)));
    consumer.poll(Duration.ofMillis(0));
    assertEquals(OptionalLong.of(40L), consumer.currentLag(tp0));
    // requests: fetch
    assertEquals(1, client.inFlightRequestCount());
    // one successful fetch should update the log end offset and the position
    final FetchInfo fetchInfo = new FetchInfo(1L, 99L, 50L, 5);
    client.respond(fetchResponse(singletonMap(tp0, fetchInfo)));
    final ConsumerRecords<String, String> records = consumer.poll(Duration.ofMillis(1));
    assertEquals(5, records.count());
    assertEquals(55L, consumer.position(tp0));
    // correct lag result
    assertEquals(OptionalLong.of(45L), consumer.currentLag(tp0));
    consumer.close(Duration.ZERO);
}
Also used : ConsumerMetadata(org.apache.kafka.clients.consumer.internals.ConsumerMetadata) MockClient(org.apache.kafka.clients.MockClient) Test(org.junit.jupiter.api.Test)

Aggregations

MockClient (org.apache.kafka.clients.MockClient)46 ConsumerMetadata (org.apache.kafka.clients.consumer.internals.ConsumerMetadata)46 Test (org.junit.jupiter.api.Test)41 Node (org.apache.kafka.common.Node)35 HashMap (java.util.HashMap)10 LinkedHashMap (java.util.LinkedHashMap)10 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)7 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)7 TopicPartition (org.apache.kafka.common.TopicPartition)7 SubscriptionState (org.apache.kafka.clients.consumer.internals.SubscriptionState)6 LogContext (org.apache.kafka.common.utils.LogContext)6 MockTime (org.apache.kafka.common.utils.MockTime)5 Time (org.apache.kafka.common.utils.Time)5 OptionalLong (java.util.OptionalLong)4 ClientRequest (org.apache.kafka.clients.ClientRequest)4 ScheduledExecutorService (java.util.concurrent.ScheduledExecutorService)3 Cluster (org.apache.kafka.common.Cluster)3 FetchRequest (org.apache.kafka.common.requests.FetchRequest)3 ExecutorService (java.util.concurrent.ExecutorService)2 ConsumerMetrics (org.apache.kafka.clients.consumer.internals.ConsumerMetrics)2