Search in sources :

Example 1 with MockClient

use of org.apache.kafka.clients.MockClient in project kafka by apache.

the class KafkaConsumerTest method testPollThrowsInterruptExceptionIfInterrupted.

@Test
public void testPollThrowsInterruptExceptionIfInterrupted() throws Exception {
    int rebalanceTimeoutMs = 60000;
    int sessionTimeoutMs = 30000;
    int heartbeatIntervalMs = 3000;
    final Time time = new MockTime();
    Cluster cluster = TestUtils.singletonCluster(topic, 1);
    final Node node = cluster.nodes().get(0);
    Metadata metadata = new Metadata(0, Long.MAX_VALUE);
    metadata.update(cluster, Collections.<String>emptySet(), time.milliseconds());
    final MockClient client = new MockClient(time, metadata);
    client.setNode(node);
    final PartitionAssignor assignor = new RoundRobinAssignor();
    final KafkaConsumer<String, String> consumer = newConsumer(time, client, metadata, assignor, rebalanceTimeoutMs, sessionTimeoutMs, heartbeatIntervalMs, false, 0);
    consumer.subscribe(Arrays.asList(topic), getConsumerRebalanceListener(consumer));
    prepareRebalance(client, node, assignor, Arrays.asList(tp0), null);
    consumer.poll(0);
    // interrupt the thread and call poll
    try {
        Thread.currentThread().interrupt();
        expectedException.expect(InterruptException.class);
        consumer.poll(0);
    } finally {
        // clear interrupted state again since this thread may be reused by JUnit
        Thread.interrupted();
    }
}
Also used : 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 2 with MockClient

use of org.apache.kafka.clients.MockClient in project kafka by apache.

the class KafkaConsumerTest method consumerCloseTest.

private void consumerCloseTest(final long closeTimeoutMs, List<? extends AbstractResponse> responses, long waitMs, boolean interrupt) throws Exception {
    int rebalanceTimeoutMs = 60000;
    int sessionTimeoutMs = 30000;
    int heartbeatIntervalMs = 5000;
    Time time = new MockTime();
    Cluster cluster = TestUtils.singletonCluster(topic, 1);
    Node node = cluster.nodes().get(0);
    Metadata metadata = new Metadata(0, Long.MAX_VALUE);
    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, rebalanceTimeoutMs, sessionTimeoutMs, heartbeatIntervalMs, false, 1000);
    consumer.subscribe(Arrays.asList(topic), getConsumerRebalanceListener(consumer));
    Node coordinator = prepareRebalance(client, node, assignor, Arrays.asList(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<Exception>();
    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));
        // Make sure that close task completes and another task can be run on the single threaded executor
        executor.submit(new Runnable() {

            @Override
            public void run() {
            }
        }).get(500, TimeUnit.MILLISECONDS);
        if (!interrupt) {
            // Should succeed without TimeoutException or ExecutionException
            future.get(500, TimeUnit.MILLISECONDS);
            assertNull("Unexpected exception during close", closeException.get());
        } else
            assertTrue("Expected exception not thrown " + closeException, closeException.get() instanceof InterruptException);
    } 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) InterruptException(org.apache.kafka.common.errors.InterruptException) ExpectedException(org.junit.rules.ExpectedException) ExecutorService(java.util.concurrent.ExecutorService) 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 3 with MockClient

use of org.apache.kafka.clients.MockClient in project kafka by apache.

the class KafkaConsumerTest method prepareOffsetCommitResponse.

private AtomicBoolean prepareOffsetCommitResponse(MockClient client, Node coordinator, final Map<TopicPartition, Long> partitionOffsets) {
    final AtomicBoolean commitReceived = new AtomicBoolean(true);
    Map<TopicPartition, Errors> response = new HashMap<>();
    for (TopicPartition partition : partitionOffsets.keySet()) response.put(partition, Errors.NONE);
    client.prepareResponseFrom(new MockClient.RequestMatcher() {

        @Override
        public boolean matches(AbstractRequest body) {
            OffsetCommitRequest commitRequest = (OffsetCommitRequest) body;
            for (Map.Entry<TopicPartition, Long> partitionOffset : partitionOffsets.entrySet()) {
                OffsetCommitRequest.PartitionData partitionData = commitRequest.offsetData().get(partitionOffset.getKey());
                // verify that the expected offset has been committed
                if (partitionData.offset != partitionOffset.getValue()) {
                    commitReceived.set(false);
                    return false;
                }
            }
            return true;
        }
    }, offsetCommitResponse(response), coordinator);
    return commitReceived;
}
Also used : AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Errors(org.apache.kafka.common.protocol.Errors) OffsetCommitRequest(org.apache.kafka.common.requests.OffsetCommitRequest) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) PartitionData(org.apache.kafka.common.requests.FetchResponse.PartitionData) TopicPartition(org.apache.kafka.common.TopicPartition) AbstractRequest(org.apache.kafka.common.requests.AbstractRequest) MockClient(org.apache.kafka.clients.MockClient)

Example 4 with MockClient

use of org.apache.kafka.clients.MockClient in project kafka by apache.

the class KafkaConsumerTest method fetchResponseWithUnexpectedPartitionIsIgnored.

@Test
public void fetchResponseWithUnexpectedPartitionIsIgnored() {
    int rebalanceTimeoutMs = 60000;
    int sessionTimeoutMs = 30000;
    int heartbeatIntervalMs = 3000;
    // adjust auto commit interval lower than heartbeat so we don't need to deal with
    // a concurrent heartbeat request
    int autoCommitIntervalMs = 1000;
    Time time = new MockTime();
    Cluster cluster = TestUtils.singletonCluster(singletonMap(topic, 1));
    Node node = cluster.nodes().get(0);
    Metadata metadata = new Metadata(0, Long.MAX_VALUE);
    metadata.update(cluster, Collections.<String>emptySet(), time.milliseconds());
    MockClient client = new MockClient(time, metadata);
    client.setNode(node);
    PartitionAssignor assignor = new RangeAssignor();
    final KafkaConsumer<String, String> consumer = newConsumer(time, client, metadata, assignor, rebalanceTimeoutMs, sessionTimeoutMs, heartbeatIntervalMs, true, autoCommitIntervalMs);
    consumer.subscribe(singletonList(topic), getConsumerRebalanceListener(consumer));
    prepareRebalance(client, node, assignor, singletonList(tp0), null);
    Map<TopicPartition, FetchInfo> fetches1 = new HashMap<>();
    fetches1.put(tp0, new FetchInfo(0, 1));
    // not assigned and not fetched
    fetches1.put(t2p0, new FetchInfo(0, 10));
    client.prepareResponseFrom(fetchResponse(fetches1), node);
    ConsumerRecords<String, String> records = consumer.poll(0);
    assertEquals(0, records.count());
}
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 5 with MockClient

use of org.apache.kafka.clients.MockClient in project kafka by apache.

the class KafkaConsumerTest method testManualAssignmentChangeWithAutoCommitDisabled.

@Test
public void testManualAssignmentChangeWithAutoCommitDisabled() {
    int rebalanceTimeoutMs = 60000;
    int sessionTimeoutMs = 30000;
    int heartbeatIntervalMs = 3000;
    int autoCommitIntervalMs = 1000;
    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 = new Metadata(0, Long.MAX_VALUE);
    metadata.update(cluster, Collections.<String>emptySet(), time.milliseconds());
    MockClient client = new MockClient(time, metadata);
    client.setNode(node);
    PartitionAssignor assignor = new RangeAssignor();
    final KafkaConsumer<String, String> consumer = newConsumer(time, client, metadata, assignor, rebalanceTimeoutMs, sessionTimeoutMs, heartbeatIntervalMs, false, autoCommitIntervalMs);
    // lookup coordinator
    client.prepareResponseFrom(new GroupCoordinatorResponse(Errors.NONE, node), node);
    Node coordinator = new Node(Integer.MAX_VALUE - node.id(), node.host(), node.port());
    // manual assignment
    consumer.assign(Arrays.asList(tp0));
    consumer.seekToBeginning(Arrays.asList(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(Collections.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), Errors.NONE));
    client.prepareResponse(fetchResponse(tp0, 10L, 1));
    ConsumerRecords<String, String> records = consumer.poll(0);
    assertEquals(1, records.count());
    assertEquals(11L, consumer.position(tp0));
    // new manual assignment
    consumer.assign(Arrays.asList(t2p0));
    // verify that assignment immediately changes
    assertTrue(consumer.assignment().equals(Collections.singleton(t2p0)));
    // the auto commit is disabled, so no offset commit request should be sent
    for (ClientRequest req : client.requests()) assertTrue(req.requestBuilder().apiKey() != ApiKeys.OFFSET_COMMIT);
    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) GroupCoordinatorResponse(org.apache.kafka.common.requests.GroupCoordinatorResponse) PartitionAssignor(org.apache.kafka.clients.consumer.internals.PartitionAssignor) MockTime(org.apache.kafka.common.utils.MockTime) ClientRequest(org.apache.kafka.clients.ClientRequest) MockClient(org.apache.kafka.clients.MockClient) Test(org.junit.Test)

Aggregations

MockClient (org.apache.kafka.clients.MockClient)23 Metadata (org.apache.kafka.clients.Metadata)19 Node (org.apache.kafka.common.Node)19 MockTime (org.apache.kafka.common.utils.MockTime)19 Cluster (org.apache.kafka.common.Cluster)17 PartitionAssignor (org.apache.kafka.clients.consumer.internals.PartitionAssignor)16 Time (org.apache.kafka.common.utils.Time)16 Test (org.junit.Test)16 HashMap (java.util.HashMap)11 LinkedHashMap (java.util.LinkedHashMap)10 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)8 TopicPartition (org.apache.kafka.common.TopicPartition)6 GroupCoordinatorResponse (org.apache.kafka.common.requests.GroupCoordinatorResponse)5 Metrics (org.apache.kafka.common.metrics.Metrics)3 AbstractRequest (org.apache.kafka.common.requests.AbstractRequest)3 Before (org.junit.Before)3 ClientRequest (org.apache.kafka.clients.ClientRequest)2 WakeupException (org.apache.kafka.common.errors.WakeupException)2 HeartbeatResponse (org.apache.kafka.common.requests.HeartbeatResponse)2 ProtocolMetadata (org.apache.kafka.common.requests.JoinGroupRequest.ProtocolMetadata)2