Search in sources :

Example 26 with Metric

use of org.apache.kafka.common.Metric in project kafka by apache.

the class IntegrationTestUtils method waitForStandbyCompletion.

/**
 * Wait for streams to "finish" processing standbys, based on the (restore) consumer lag metric. Includes only the
 * restore consumer, for completion of active tasks see {@link #waitForCompletion}
 *
 * Caveats:
 * - Inputs must be finite, fully loaded, and flushed before this method is called
 * - expectedPartitions is the total number of partitions to watch the lag on, including both input and internal.
 *   It's somewhat ok to get this wrong, as the main failure case would be an immediate return due to the clients
 *   not being initialized, which you can avoid with any non-zero value. But it's probably better to get it right ;)
 */
public static void waitForStandbyCompletion(final KafkaStreams streams, final int expectedPartitions, final long timeoutMilliseconds) {
    final long start = System.currentTimeMillis();
    while (true) {
        int lagMetrics = 0;
        double totalLag = 0.0;
        for (final Metric metric : streams.metrics().values()) {
            if (metric.metricName().name().equals("records-lag")) {
                if (metric.metricName().tags().get("client-id").endsWith("restore-consumer")) {
                    lagMetrics++;
                    totalLag += ((Number) metric.metricValue()).doubleValue();
                }
            }
        }
        if (lagMetrics >= expectedPartitions && totalLag == 0.0) {
            return;
        }
        if (System.currentTimeMillis() - start >= timeoutMilliseconds) {
            throw new RuntimeException(String.format("Timed out waiting for completion. lagMetrics=[%s/%s] totalLag=[%s]", lagMetrics, expectedPartitions, totalLag));
        }
    }
}
Also used : Metric(org.apache.kafka.common.Metric)

Example 27 with Metric

use of org.apache.kafka.common.Metric in project kafka by apache.

the class KafkaConsumerTest method testMeasureCommitSyncDurationOnFailure.

@Test
public void testMeasureCommitSyncDurationOnFailure() {
    final KafkaConsumer<String, String> consumer = consumerWithPendingError(new MockTime(Duration.ofSeconds(1).toMillis()));
    try {
        consumer.commitSync(Collections.singletonMap(tp0, new OffsetAndMetadata(10L)));
    } catch (final RuntimeException e) {
    }
    final Metric metric = consumer.metrics().get(consumer.metrics.metricName("commit-sync-time-ns-total", "consumer-metrics"));
    assertTrue((Double) metric.metricValue() >= Duration.ofMillis(999).toNanos());
}
Also used : Metric(org.apache.kafka.common.Metric) MockTime(org.apache.kafka.common.utils.MockTime) Test(org.junit.jupiter.api.Test)

Example 28 with Metric

use of org.apache.kafka.common.Metric in project kafka by apache.

the class KafkaConsumerTest method testMeasureCommitSyncDuration.

@Test
public void testMeasureCommitSyncDuration() {
    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));
    client.prepareResponseFrom(FindCoordinatorResponse.prepareResponse(Errors.NONE, groupId, node), node);
    Node coordinator = new Node(Integer.MAX_VALUE - node.id(), node.host(), node.port());
    client.prepareResponseFrom(offsetCommitResponse(Collections.singletonMap(tp0, Errors.NONE)), coordinator);
    consumer.commitSync(Collections.singletonMap(tp0, new OffsetAndMetadata(10L)));
    final Metric metric = consumer.metrics().get(consumer.metrics.metricName("commit-sync-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 29 with Metric

use of org.apache.kafka.common.Metric in project kafka by apache.

the class KafkaConsumerTest method testMeasureCommittedDurationOnFailure.

@Test
public void testMeasureCommittedDurationOnFailure() {
    final KafkaConsumer<String, String> consumer = consumerWithPendingError(new MockTime(Duration.ofSeconds(1).toMillis()));
    try {
        consumer.committed(Collections.singleton(tp0));
    } catch (final RuntimeException e) {
    }
    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 : Metric(org.apache.kafka.common.Metric) MockTime(org.apache.kafka.common.utils.MockTime) Test(org.junit.jupiter.api.Test)

Example 30 with Metric

use of org.apache.kafka.common.Metric in project kafka by apache.

the class ConsumerCoordinatorTest method testThreadSafeAssignedPartitionsMetric.

@Test
public void testThreadSafeAssignedPartitionsMetric() throws Exception {
    // Get the assigned-partitions metric
    final Metric metric = metrics.metric(new MetricName("assigned-partitions", consumerId + groupId + "-coordinator-metrics", "", Collections.emptyMap()));
    // Start polling the metric in the background
    final AtomicBoolean doStop = new AtomicBoolean();
    final AtomicReference<Exception> exceptionHolder = new AtomicReference<>();
    final AtomicInteger observedSize = new AtomicInteger();
    Thread poller = new Thread() {

        @Override
        public void run() {
            // Poll as fast as possible to reproduce ConcurrentModificationException
            while (!doStop.get()) {
                try {
                    int size = ((Double) metric.metricValue()).intValue();
                    observedSize.set(size);
                } catch (Exception e) {
                    exceptionHolder.set(e);
                    return;
                }
            }
        }
    };
    poller.start();
    // Assign two partitions to trigger a metric change that can lead to ConcurrentModificationException
    client.prepareResponse(groupCoordinatorResponse(node, Errors.NONE));
    coordinator.ensureCoordinatorReady(time.timer(Long.MAX_VALUE));
    // Change the assignment several times to increase likelihood of concurrent updates
    Set<TopicPartition> partitions = new HashSet<>();
    int totalPartitions = 10;
    for (int partition = 0; partition < totalPartitions; partition++) {
        partitions.add(new TopicPartition(topic1, partition));
        subscriptions.assignFromUser(partitions);
    }
    // Wait for the metric poller to observe the final assignment change or raise an error
    TestUtils.waitForCondition(() -> observedSize.get() == totalPartitions || exceptionHolder.get() != null, "Failed to observe expected assignment change");
    doStop.set(true);
    poller.join();
    assertNull(exceptionHolder.get(), "Failed fetching the metric at least once");
}
Also used : AtomicReference(java.util.concurrent.atomic.AtomicReference) KafkaException(org.apache.kafka.common.KafkaException) AuthenticationException(org.apache.kafka.common.errors.AuthenticationException) RetriableCommitFailedException(org.apache.kafka.clients.consumer.RetriableCommitFailedException) FencedInstanceIdException(org.apache.kafka.common.errors.FencedInstanceIdException) CommitFailedException(org.apache.kafka.clients.consumer.CommitFailedException) UnsupportedVersionException(org.apache.kafka.common.errors.UnsupportedVersionException) GroupAuthorizationException(org.apache.kafka.common.errors.GroupAuthorizationException) TimeoutException(java.util.concurrent.TimeoutException) WakeupException(org.apache.kafka.common.errors.WakeupException) RebalanceInProgressException(org.apache.kafka.common.errors.RebalanceInProgressException) DisconnectException(org.apache.kafka.common.errors.DisconnectException) TopicAuthorizationException(org.apache.kafka.common.errors.TopicAuthorizationException) ApiException(org.apache.kafka.common.errors.ApiException) MetricName(org.apache.kafka.common.MetricName) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) TopicPartition(org.apache.kafka.common.TopicPartition) Metric(org.apache.kafka.common.Metric) KafkaMetric(org.apache.kafka.common.metrics.KafkaMetric) HashSet(java.util.HashSet) Test(org.junit.jupiter.api.Test)

Aggregations

Metric (org.apache.kafka.common.Metric)42 MetricName (org.apache.kafka.common.MetricName)24 Test (org.junit.Test)18 MockTime (org.apache.kafka.common.utils.MockTime)14 StreamsConfig (org.apache.kafka.streams.StreamsConfig)13 Map (java.util.Map)11 Test (org.junit.jupiter.api.Test)11 Metrics (org.apache.kafka.common.metrics.Metrics)10 Collections (java.util.Collections)9 HashMap (java.util.HashMap)9 Properties (java.util.Properties)9 KafkaMetric (org.apache.kafka.common.metrics.KafkaMetric)9 StreamsMetricsImpl (org.apache.kafka.streams.processor.internals.metrics.StreamsMetricsImpl)9 ArrayList (java.util.ArrayList)8 TaskId (org.apache.kafka.streams.processor.TaskId)8 List (java.util.List)7 TopicPartition (org.apache.kafka.common.TopicPartition)7 StreamsException (org.apache.kafka.streams.errors.StreamsException)7 MatcherAssert.assertThat (org.hamcrest.MatcherAssert.assertThat)7 Utils.mkMap (org.apache.kafka.common.utils.Utils.mkMap)6