Search in sources :

Example 11 with Time

use of org.apache.kafka.common.utils.Time in project apache-kafka-on-k8s by banzaicloud.

the class KafkaConsumerTest method testManualAssignmentChangeWithAutoCommitEnabled.

@Test
public void testManualAssignmentChangeWithAutoCommitEnabled() {
    Time time = new MockTime();
    Map<String, Integer> tpCounts = new HashMap<>();
    tpCounts.put(topic, 1);
    tpCounts.put(topic2, 1);
    Cluster cluster = TestUtils.singletonCluster(tpCounts);
    Node node = cluster.nodes().get(0);
    Metadata metadata = createMetadata();
    metadata.update(cluster, Collections.<String>emptySet(), time.milliseconds());
    MockClient client = new MockClient(time, metadata);
    client.setNode(node);
    PartitionAssignor assignor = new RangeAssignor();
    KafkaConsumer<String, String> consumer = newConsumer(time, client, metadata, assignor, true);
    // lookup coordinator
    client.prepareResponseFrom(new FindCoordinatorResponse(Errors.NONE, node), node);
    Node coordinator = new Node(Integer.MAX_VALUE - node.id(), node.host(), node.port());
    // manual assignment
    consumer.assign(singleton(tp0));
    consumer.seekToBeginning(singleton(tp0));
    // fetch offset for one topic
    client.prepareResponseFrom(offsetResponse(Collections.singletonMap(tp0, 0L), Errors.NONE), coordinator);
    assertEquals(0, consumer.committed(tp0).offset());
    // verify that assignment immediately changes
    assertTrue(consumer.assignment().equals(singleton(tp0)));
    // there shouldn't be any need to lookup the coordinator or fetch committed offsets.
    // we just lookup the starting position and send the record fetch.
    client.prepareResponse(listOffsetsResponse(Collections.singletonMap(tp0, 10L)));
    client.prepareResponse(fetchResponse(tp0, 10L, 1));
    ConsumerRecords<String, String> records = consumer.poll(5);
    assertEquals(1, records.count());
    assertEquals(11L, consumer.position(tp0));
    // mock the offset commit response for to be revoked partitions
    AtomicBoolean commitReceived = prepareOffsetCommitResponse(client, coordinator, tp0, 11);
    // new manual assignment
    consumer.assign(singleton(t2p0));
    // verify that assignment immediately changes
    assertTrue(consumer.assignment().equals(singleton(t2p0)));
    // verify that the offset commits occurred as expected
    assertTrue(commitReceived.get());
    client.requests().clear();
    consumer.close();
}
Also used : FindCoordinatorResponse(org.apache.kafka.common.requests.FindCoordinatorResponse) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) Node(org.apache.kafka.common.Node) Metadata(org.apache.kafka.clients.Metadata) Cluster(org.apache.kafka.common.Cluster) MockTime(org.apache.kafka.common.utils.MockTime) Time(org.apache.kafka.common.utils.Time) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) PartitionAssignor(org.apache.kafka.clients.consumer.internals.PartitionAssignor) MockTime(org.apache.kafka.common.utils.MockTime) MockClient(org.apache.kafka.clients.MockClient) Test(org.junit.Test)

Example 12 with Time

use of org.apache.kafka.common.utils.Time in project apache-kafka-on-k8s by banzaicloud.

the class KafkaConsumerTest method testChangingRegexSubscription.

@Test
public void testChangingRegexSubscription() {
    PartitionAssignor assignor = new RoundRobinAssignor();
    String otherTopic = "other";
    TopicPartition otherTopicPartition = new TopicPartition(otherTopic, 0);
    Time time = new MockTime();
    Map<String, Integer> topicMetadata = new HashMap<>();
    topicMetadata.put(topic, 1);
    topicMetadata.put(otherTopic, 1);
    Cluster cluster = TestUtils.clusterWith(1, topicMetadata);
    Metadata metadata = createMetadata();
    Node node = cluster.nodes().get(0);
    MockClient client = new MockClient(time, metadata);
    client.setNode(node);
    client.cluster(cluster);
    metadata.update(cluster, Collections.<String>emptySet(), time.milliseconds());
    KafkaConsumer<String, String> consumer = newConsumer(time, client, metadata, assignor, false);
    Node coordinator = prepareRebalance(client, node, singleton(topic), assignor, singletonList(tp0), null);
    consumer.subscribe(Pattern.compile(topic), getConsumerRebalanceListener(consumer));
    consumer.poll(0);
    assertEquals(singleton(topic), consumer.subscription());
    consumer.subscribe(Pattern.compile(otherTopic), getConsumerRebalanceListener(consumer));
    prepareRebalance(client, node, singleton(otherTopic), assignor, singletonList(otherTopicPartition), coordinator);
    consumer.poll(0);
    assertEquals(singleton(otherTopic), consumer.subscription());
    consumer.close(0, TimeUnit.MILLISECONDS);
}
Also used : HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) Node(org.apache.kafka.common.Node) Metadata(org.apache.kafka.clients.Metadata) Cluster(org.apache.kafka.common.Cluster) MockTime(org.apache.kafka.common.utils.MockTime) Time(org.apache.kafka.common.utils.Time) TopicPartition(org.apache.kafka.common.TopicPartition) PartitionAssignor(org.apache.kafka.clients.consumer.internals.PartitionAssignor) MockTime(org.apache.kafka.common.utils.MockTime) MockClient(org.apache.kafka.clients.MockClient) Test(org.junit.Test)

Example 13 with Time

use of org.apache.kafka.common.utils.Time in project apache-kafka-on-k8s by banzaicloud.

the class KafkaConsumerTest method consumerCloseTest.

private void consumerCloseTest(final long closeTimeoutMs, List<? extends AbstractResponse> responses, long waitMs, boolean interrupt) throws Exception {
    Time time = new MockTime();
    Cluster cluster = TestUtils.singletonCluster(topic, 1);
    Node node = cluster.nodes().get(0);
    Metadata metadata = createMetadata();
    metadata.update(cluster, Collections.<String>emptySet(), time.milliseconds());
    MockClient client = new MockClient(time, metadata);
    client.setNode(node);
    PartitionAssignor assignor = new RoundRobinAssignor();
    final KafkaConsumer<String, String> consumer = newConsumer(time, client, metadata, assignor, false);
    consumer.subscribe(singleton(topic), getConsumerRebalanceListener(consumer));
    Node coordinator = prepareRebalance(client, node, assignor, singletonList(tp0), null);
    client.prepareMetadataUpdate(cluster, Collections.<String>emptySet());
    // Poll with responses
    client.prepareResponseFrom(fetchResponse(tp0, 0, 1), node);
    client.prepareResponseFrom(fetchResponse(tp0, 1, 0), node);
    consumer.poll(0);
    // Initiate close() after a commit request on another thread.
    // Kafka consumer is single-threaded, but the implementation allows calls on a
    // different thread as long as the calls are not executed concurrently. So this is safe.
    ExecutorService executor = Executors.newSingleThreadExecutor();
    final AtomicReference<Exception> closeException = new AtomicReference<>();
    try {
        Future<?> future = executor.submit(new Runnable() {

            @Override
            public void run() {
                consumer.commitAsync();
                try {
                    consumer.close(closeTimeoutMs, TimeUnit.MILLISECONDS);
                } catch (Exception e) {
                    closeException.set(e);
                }
            }
        });
        // if close timeout is not zero.
        try {
            future.get(100, TimeUnit.MILLISECONDS);
            if (closeTimeoutMs != 0)
                fail("Close completed without waiting for commit or leave response");
        } catch (TimeoutException e) {
        // Expected exception
        }
        // Ensure close has started and queued at least one more request after commitAsync
        client.waitForRequests(2, 1000);
        // In non-graceful mode, close() times out without an exception even though commit response is pending
        for (int i = 0; i < responses.size(); i++) {
            client.waitForRequests(1, 1000);
            client.respondFrom(responses.get(i), coordinator);
            if (i != responses.size() - 1) {
                try {
                    future.get(100, TimeUnit.MILLISECONDS);
                    fail("Close completed without waiting for response");
                } catch (TimeoutException e) {
                // Expected exception
                }
            }
        }
        if (waitMs > 0)
            time.sleep(waitMs);
        if (interrupt) {
            assertTrue("Close terminated prematurely", future.cancel(true));
            TestUtils.waitForCondition(new TestCondition() {

                @Override
                public boolean conditionMet() {
                    return closeException.get() != null;
                }
            }, "InterruptException did not occur within timeout.");
            assertTrue("Expected exception not thrown " + closeException, closeException.get() instanceof InterruptException);
        } else {
            // Should succeed without TimeoutException or ExecutionException
            future.get(500, TimeUnit.MILLISECONDS);
            assertNull("Unexpected exception during close", closeException.get());
        }
    } finally {
        executor.shutdownNow();
    }
}
Also used : Node(org.apache.kafka.common.Node) Metadata(org.apache.kafka.clients.Metadata) InterruptException(org.apache.kafka.common.errors.InterruptException) Cluster(org.apache.kafka.common.Cluster) MockTime(org.apache.kafka.common.utils.MockTime) Time(org.apache.kafka.common.utils.Time) AtomicReference(java.util.concurrent.atomic.AtomicReference) KafkaException(org.apache.kafka.common.KafkaException) TimeoutException(java.util.concurrent.TimeoutException) WakeupException(org.apache.kafka.common.errors.WakeupException) AuthenticationException(org.apache.kafka.common.errors.AuthenticationException) InterruptException(org.apache.kafka.common.errors.InterruptException) ExpectedException(org.junit.rules.ExpectedException) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) ExecutorService(java.util.concurrent.ExecutorService) TestCondition(org.apache.kafka.test.TestCondition) PartitionAssignor(org.apache.kafka.clients.consumer.internals.PartitionAssignor) MockTime(org.apache.kafka.common.utils.MockTime) MockClient(org.apache.kafka.clients.MockClient) TimeoutException(java.util.concurrent.TimeoutException)

Example 14 with Time

use of org.apache.kafka.common.utils.Time in project apache-kafka-on-k8s by banzaicloud.

the class KafkaConsumerTest method testConsumerWithinBlackoutPeriodAfterAuthenticationFailure.

@Test
public void testConsumerWithinBlackoutPeriodAfterAuthenticationFailure() {
    Time time = new MockTime();
    Map<String, Integer> tpCounts = new HashMap<>();
    tpCounts.put(topic, 1);
    Cluster cluster = TestUtils.singletonCluster(tpCounts);
    Node node = cluster.nodes().get(0);
    Metadata metadata = createMetadata();
    metadata.update(cluster, Collections.<String>emptySet(), time.milliseconds());
    MockClient client = new MockClient(time, metadata);
    client.setNode(node);
    client.authenticationFailed(node, 300);
    PartitionAssignor assignor = new RangeAssignor();
    final KafkaConsumer<String, String> consumer = newConsumer(time, client, metadata, assignor, true);
    consumer.subscribe(Collections.singleton(topic));
    callConsumerApisAndExpectAnAuthenticationError(consumer, tp0);
    // wait less than the blackout period
    time.sleep(30);
    assertTrue(client.connectionFailed(node));
    callConsumerApisAndExpectAnAuthenticationError(consumer, tp0);
    client.requests().clear();
    consumer.close(0, TimeUnit.MILLISECONDS);
}
Also used : HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) Node(org.apache.kafka.common.Node) Metadata(org.apache.kafka.clients.Metadata) Cluster(org.apache.kafka.common.Cluster) MockTime(org.apache.kafka.common.utils.MockTime) Time(org.apache.kafka.common.utils.Time) PartitionAssignor(org.apache.kafka.clients.consumer.internals.PartitionAssignor) MockTime(org.apache.kafka.common.utils.MockTime) MockClient(org.apache.kafka.clients.MockClient) Test(org.junit.Test)

Example 15 with Time

use of org.apache.kafka.common.utils.Time in project apache-kafka-on-k8s by banzaicloud.

the class KafkaConsumerTest method testSubscriptionChangesWithAutoCommitEnabled.

/**
 * Verify that when a consumer changes its topic subscription its assigned partitions
 * do not immediately change, and the latest consumed offsets of its to-be-revoked
 * partitions are properly committed (when auto-commit is enabled).
 * Upon unsubscribing from subscribed topics the consumer subscription and assignment
 * are both updated right away but its consumed offsets are not auto committed.
 */
@Test
public void testSubscriptionChangesWithAutoCommitEnabled() {
    Time time = new MockTime();
    Map<String, Integer> tpCounts = new HashMap<>();
    tpCounts.put(topic, 1);
    tpCounts.put(topic2, 1);
    tpCounts.put(topic3, 1);
    Cluster cluster = TestUtils.singletonCluster(tpCounts);
    Node node = cluster.nodes().get(0);
    Metadata metadata = createMetadata();
    metadata.update(cluster, Collections.<String>emptySet(), time.milliseconds());
    MockClient client = new MockClient(time, metadata);
    client.setNode(node);
    PartitionAssignor assignor = new RangeAssignor();
    KafkaConsumer<String, String> consumer = newConsumer(time, client, metadata, assignor, true);
    // initial subscription
    consumer.subscribe(Arrays.asList(topic, topic2), getConsumerRebalanceListener(consumer));
    // verify that subscription has changed but assignment is still unchanged
    assertTrue(consumer.subscription().size() == 2);
    assertTrue(consumer.subscription().contains(topic) && consumer.subscription().contains(topic2));
    assertTrue(consumer.assignment().isEmpty());
    // mock rebalance responses
    Node coordinator = prepareRebalance(client, node, assignor, Arrays.asList(tp0, t2p0), null);
    consumer.poll(0);
    // verify that subscription is still the same, and now assignment has caught up
    assertTrue(consumer.subscription().size() == 2);
    assertTrue(consumer.subscription().contains(topic) && consumer.subscription().contains(topic2));
    assertTrue(consumer.assignment().size() == 2);
    assertTrue(consumer.assignment().contains(tp0) && consumer.assignment().contains(t2p0));
    // mock a response to the outstanding fetch so that we have data available on the next poll
    Map<TopicPartition, FetchInfo> fetches1 = new HashMap<>();
    fetches1.put(tp0, new FetchInfo(0, 1));
    fetches1.put(t2p0, new FetchInfo(0, 10));
    client.respondFrom(fetchResponse(fetches1), node);
    client.poll(0, time.milliseconds());
    ConsumerRecords<String, String> records = consumer.poll(0);
    // clear out the prefetch so it doesn't interfere with the rest of the test
    fetches1.put(tp0, new FetchInfo(1, 0));
    fetches1.put(t2p0, new FetchInfo(10, 0));
    client.respondFrom(fetchResponse(fetches1), node);
    client.poll(0, time.milliseconds());
    // verify that the fetch occurred as expected
    assertEquals(11, records.count());
    assertEquals(1L, consumer.position(tp0));
    assertEquals(10L, consumer.position(t2p0));
    // subscription change
    consumer.subscribe(Arrays.asList(topic, topic3), getConsumerRebalanceListener(consumer));
    // verify that subscription has changed but assignment is still unchanged
    assertTrue(consumer.subscription().size() == 2);
    assertTrue(consumer.subscription().contains(topic) && consumer.subscription().contains(topic3));
    assertTrue(consumer.assignment().size() == 2);
    assertTrue(consumer.assignment().contains(tp0) && consumer.assignment().contains(t2p0));
    // mock the offset commit response for to be revoked partitions
    Map<TopicPartition, Long> partitionOffsets1 = new HashMap<>();
    partitionOffsets1.put(tp0, 1L);
    partitionOffsets1.put(t2p0, 10L);
    AtomicBoolean commitReceived = prepareOffsetCommitResponse(client, coordinator, partitionOffsets1);
    // mock rebalance responses
    prepareRebalance(client, node, assignor, Arrays.asList(tp0, t3p0), coordinator);
    // mock a response to the next fetch from the new assignment
    Map<TopicPartition, FetchInfo> fetches2 = new HashMap<>();
    fetches2.put(tp0, new FetchInfo(1, 1));
    fetches2.put(t3p0, new FetchInfo(0, 100));
    client.prepareResponse(fetchResponse(fetches2));
    records = consumer.poll(0);
    // verify that the fetch occurred as expected
    assertEquals(101, records.count());
    assertEquals(2L, consumer.position(tp0));
    assertEquals(100L, consumer.position(t3p0));
    // verify that the offset commits occurred as expected
    assertTrue(commitReceived.get());
    // verify that subscription is still the same, and now assignment has caught up
    assertTrue(consumer.subscription().size() == 2);
    assertTrue(consumer.subscription().contains(topic) && consumer.subscription().contains(topic3));
    assertTrue(consumer.assignment().size() == 2);
    assertTrue(consumer.assignment().contains(tp0) && consumer.assignment().contains(t3p0));
    consumer.unsubscribe();
    // verify that subscription and assignment are both cleared
    assertTrue(consumer.subscription().isEmpty());
    assertTrue(consumer.assignment().isEmpty());
    client.requests().clear();
    consumer.close();
}
Also used : HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) Node(org.apache.kafka.common.Node) Metadata(org.apache.kafka.clients.Metadata) Cluster(org.apache.kafka.common.Cluster) MockTime(org.apache.kafka.common.utils.MockTime) Time(org.apache.kafka.common.utils.Time) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) TopicPartition(org.apache.kafka.common.TopicPartition) PartitionAssignor(org.apache.kafka.clients.consumer.internals.PartitionAssignor) MockTime(org.apache.kafka.common.utils.MockTime) MockClient(org.apache.kafka.clients.MockClient) Test(org.junit.Test)

Aggregations

Time (org.apache.kafka.common.utils.Time)125 MockTime (org.apache.kafka.common.utils.MockTime)107 Test (org.junit.jupiter.api.Test)63 MockClient (org.apache.kafka.clients.MockClient)55 HashMap (java.util.HashMap)53 Cluster (org.apache.kafka.common.Cluster)41 Test (org.junit.Test)40 Node (org.apache.kafka.common.Node)39 ParameterizedTest (org.junit.jupiter.params.ParameterizedTest)32 MetadataResponse (org.apache.kafka.common.requests.MetadataResponse)31 StringSerializer (org.apache.kafka.common.serialization.StringSerializer)30 Metadata (org.apache.kafka.clients.Metadata)28 ProducerMetadata (org.apache.kafka.clients.producer.internals.ProducerMetadata)25 TopicPartition (org.apache.kafka.common.TopicPartition)22 PartitionAssignor (org.apache.kafka.clients.consumer.internals.PartitionAssignor)21 LogContext (org.apache.kafka.common.utils.LogContext)17 Map (java.util.Map)14 Properties (java.util.Properties)14 MetricName (org.apache.kafka.common.MetricName)14 ExecutionException (java.util.concurrent.ExecutionException)13