Search in sources :

Example 86 with KafkaMetric

use of org.apache.kafka.common.metrics.KafkaMetric in project kafka by apache.

the class FetcherTest method testFetcherMetrics.

/*
     * Send multiple requests. Verify that the client side quota metrics have the right values
     */
@Test
public void testFetcherMetrics() {
    buildFetcher();
    assignFromUser(singleton(tp0));
    subscriptions.seek(tp0, 0);
    MetricName maxLagMetric = metrics.metricInstance(metricsRegistry.recordsLagMax);
    Map<String, String> tags = new HashMap<>();
    tags.put("topic", tp0.topic());
    tags.put("partition", String.valueOf(tp0.partition()));
    MetricName partitionLagMetric = metrics.metricName("records-lag", metricGroup, tags);
    Map<MetricName, KafkaMetric> allMetrics = metrics.metrics();
    KafkaMetric recordsFetchLagMax = allMetrics.get(maxLagMetric);
    // recordsFetchLagMax should be initialized to NaN
    assertEquals(Double.NaN, (Double) recordsFetchLagMax.metricValue(), EPSILON);
    // recordsFetchLagMax should be hw - fetchOffset after receiving an empty FetchResponse
    fetchRecords(tidp0, MemoryRecords.EMPTY, Errors.NONE, 100L, 0);
    assertEquals(100, (Double) recordsFetchLagMax.metricValue(), EPSILON);
    KafkaMetric partitionLag = allMetrics.get(partitionLagMetric);
    assertEquals(100, (Double) partitionLag.metricValue(), EPSILON);
    // recordsFetchLagMax should be hw - offset of the last message after receiving a non-empty FetchResponse
    MemoryRecordsBuilder builder = MemoryRecords.builder(ByteBuffer.allocate(1024), CompressionType.NONE, TimestampType.CREATE_TIME, 0L);
    for (int v = 0; v < 3; v++) builder.appendWithOffset(v, RecordBatch.NO_TIMESTAMP, "key".getBytes(), ("value-" + v).getBytes());
    fetchRecords(tidp0, builder.build(), Errors.NONE, 200L, 0);
    assertEquals(197, (Double) recordsFetchLagMax.metricValue(), EPSILON);
    assertEquals(197, (Double) partitionLag.metricValue(), EPSILON);
    // verify de-registration of partition lag
    subscriptions.unsubscribe();
    fetcher.sendFetches();
    assertFalse(allMetrics.containsKey(partitionLagMetric));
}
Also used : MetricName(org.apache.kafka.common.MetricName) LinkedHashMap(java.util.LinkedHashMap) HashMap(java.util.HashMap) MemoryRecordsBuilder(org.apache.kafka.common.record.MemoryRecordsBuilder) KafkaMetric(org.apache.kafka.common.metrics.KafkaMetric) Test(org.junit.jupiter.api.Test)

Example 87 with KafkaMetric

use of org.apache.kafka.common.metrics.KafkaMetric in project kafka by apache.

the class StreamThreadTest method shouldConstructAdminMetrics.

@Test
public void shouldConstructAdminMetrics() {
    final Node broker1 = new Node(0, "dummyHost-1", 1234);
    final Node broker2 = new Node(1, "dummyHost-2", 1234);
    final List<Node> cluster = Arrays.asList(broker1, broker2);
    final MockAdminClient adminClient = new MockAdminClient.Builder().brokers(cluster).clusterId(null).build();
    final Consumer<byte[], byte[]> consumer = EasyMock.createNiceMock(Consumer.class);
    final ConsumerGroupMetadata consumerGroupMetadata = mock(ConsumerGroupMetadata.class);
    expect(consumer.groupMetadata()).andStubReturn(consumerGroupMetadata);
    expect(consumerGroupMetadata.groupInstanceId()).andReturn(Optional.empty());
    EasyMock.replay(consumer, consumerGroupMetadata);
    final TaskManager taskManager = EasyMock.createNiceMock(TaskManager.class);
    final StreamsMetricsImpl streamsMetrics = new StreamsMetricsImpl(metrics, CLIENT_ID, StreamsConfig.METRICS_LATEST, mockTime);
    final TopologyMetadata topologyMetadata = new TopologyMetadata(internalTopologyBuilder, config);
    topologyMetadata.buildAndRewriteTopology();
    final StreamThread thread = new StreamThread(mockTime, config, adminClient, consumer, consumer, null, null, taskManager, streamsMetrics, topologyMetadata, CLIENT_ID, new LogContext(""), new AtomicInteger(), new AtomicLong(Long.MAX_VALUE), new LinkedList<>(), null, HANDLER, null);
    final MetricName testMetricName = new MetricName("test_metric", "", "", new HashMap<>());
    final Metric testMetric = new KafkaMetric(new Object(), testMetricName, (Measurable) (config, now) -> 0, null, new MockTime());
    EasyMock.replay(taskManager);
    adminClient.setMockMetrics(testMetricName, testMetric);
    final Map<MetricName, Metric> adminClientMetrics = thread.adminClientMetrics();
    assertEquals(testMetricName, adminClientMetrics.get(testMetricName).metricName());
}
Also used : MockTime(org.apache.kafka.common.utils.MockTime) Arrays(java.util.Arrays) ConsumedInternal(org.apache.kafka.streams.kstream.internals.ConsumedInternal) ConsumerGroupMetadata(org.apache.kafka.clients.consumer.ConsumerGroupMetadata) KafkaException(org.apache.kafka.common.KafkaException) Utils.mkProperties(org.apache.kafka.common.utils.Utils.mkProperties) CoreMatchers.startsWith(org.hamcrest.CoreMatchers.startsWith) StreamsException(org.apache.kafka.streams.errors.StreamsException) ConsumerRecords(org.apache.kafka.clients.consumer.ConsumerRecords) OffsetResetStrategy(org.apache.kafka.clients.consumer.OffsetResetStrategy) MockApiProcessor(org.apache.kafka.test.MockApiProcessor) Cluster(org.apache.kafka.common.Cluster) Utils.mkMap(org.apache.kafka.common.utils.Utils.mkMap) ProcessorSupplier(org.apache.kafka.streams.processor.api.ProcessorSupplier) LogContext(org.apache.kafka.common.utils.LogContext) KeyValueStore(org.apache.kafka.streams.state.KeyValueStore) Duration(java.time.Duration) Map(java.util.Map) TimestampType(org.apache.kafka.common.record.TimestampType) MockKeyValueStoreBuilder(org.apache.kafka.test.MockKeyValueStoreBuilder) ProcessorContext(org.apache.kafka.streams.processor.api.ProcessorContext) ThreadMetadata(org.apache.kafka.streams.ThreadMetadata) TestUtils(org.apache.kafka.test.TestUtils) ReferenceContainer(org.apache.kafka.streams.processor.internals.assignment.ReferenceContainer) Utils.mkSet(org.apache.kafka.common.utils.Utils.mkSet) Set(java.util.Set) PartitionInfo(org.apache.kafka.common.PartitionInfo) Measurable(org.apache.kafka.common.metrics.Measurable) MockClientSupplier(org.apache.kafka.test.MockClientSupplier) MockAdminClient(org.apache.kafka.clients.admin.MockAdminClient) Metrics(org.apache.kafka.common.metrics.Metrics) Stream(java.util.stream.Stream) Utils.mkEntry(org.apache.kafka.common.utils.Utils.mkEntry) ConsumerRecord(org.apache.kafka.clients.consumer.ConsumerRecord) Assert.assertFalse(org.junit.Assert.assertFalse) Node(org.apache.kafka.common.Node) Matchers.is(org.hamcrest.Matchers.is) KafkaMetricsContext(org.apache.kafka.common.metrics.KafkaMetricsContext) CoreMatchers.equalTo(org.hamcrest.CoreMatchers.equalTo) EasyMock.mock(org.easymock.EasyMock.mock) ArrayList(java.util.ArrayList) MetricsContext(org.apache.kafka.common.metrics.MetricsContext) Assert.assertSame(org.junit.Assert.assertSame) CHECKPOINT_FILE_NAME(org.apache.kafka.streams.processor.internals.StateManagerUtil.CHECKPOINT_FILE_NAME) PunctuationType(org.apache.kafka.streams.processor.PunctuationType) BiConsumer(java.util.function.BiConsumer) Processor(org.apache.kafka.streams.processor.api.Processor) MatcherAssert.assertThat(org.hamcrest.MatcherAssert.assertThat) TaskCorruptedException(org.apache.kafka.streams.errors.TaskCorruptedException) Before(org.junit.Before) Properties(java.util.Properties) Producer(org.apache.kafka.clients.producer.Producer) LogAndContinueExceptionHandler(org.apache.kafka.streams.errors.LogAndContinueExceptionHandler) EasyMock.niceMock(org.easymock.EasyMock.niceMock) Assert.assertTrue(org.junit.Assert.assertTrue) Test(org.junit.Test) EasyMock(org.easymock.EasyMock) File(java.io.File) AtomicLong(java.util.concurrent.atomic.AtomicLong) Assert.assertNull(org.junit.Assert.assertNull) LogCaptureAppender(org.apache.kafka.streams.processor.internals.testutil.LogCaptureAppender) Assert(org.junit.Assert) MockProducer(org.apache.kafka.clients.producer.MockProducer) Assert.assertEquals(org.junit.Assert.assertEquals) Matchers.isA(org.hamcrest.Matchers.isA) MockConsumer(org.apache.kafka.clients.consumer.MockConsumer) Stores(org.apache.kafka.streams.state.Stores) MockRebalanceListener(org.apache.kafka.clients.consumer.internals.MockRebalanceListener) InternalStreamsBuilder(org.apache.kafka.streams.kstream.internals.InternalStreamsBuilder) LogAndSkipOnInvalidTimestamp(org.apache.kafka.streams.processor.LogAndSkipOnInvalidTimestamp) ContextualProcessor(org.apache.kafka.streams.processor.api.ContextualProcessor) Collections.singleton(java.util.Collections.singleton) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Metric(org.apache.kafka.common.Metric) MetricName(org.apache.kafka.common.MetricName) Serdes(org.apache.kafka.common.serialization.Serdes) StreamsMetricsImpl(org.apache.kafka.streams.processor.internals.metrics.StreamsMetricsImpl) Assert.fail(org.junit.Assert.fail) Consumer(org.apache.kafka.clients.consumer.Consumer) TopicPartition(org.apache.kafka.common.TopicPartition) ClientUtils.getSharedAdminClientId(org.apache.kafka.streams.processor.internals.ClientUtils.getSharedAdminClientId) Collection(java.util.Collection) KeyValue(org.apache.kafka.streams.KeyValue) UUID(java.util.UUID) MaterializedInternal(org.apache.kafka.streams.kstream.internals.MaterializedInternal) Bytes(org.apache.kafka.common.utils.Bytes) ConsumerRebalanceListener(org.apache.kafka.clients.consumer.ConsumerRebalanceListener) List(java.util.List) ProducerFencedException(org.apache.kafka.common.errors.ProducerFencedException) Materialized(org.apache.kafka.streams.kstream.Materialized) Optional(java.util.Optional) KafkaMetric(org.apache.kafka.common.metrics.KafkaMetric) StreamsConfig(org.apache.kafka.streams.StreamsConfig) TaskId(org.apache.kafka.streams.processor.TaskId) Assert.assertThrows(org.junit.Assert.assertThrows) CoreMatchers.not(org.hamcrest.CoreMatchers.not) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) HashMap(java.util.HashMap) HashSet(java.util.HashSet) RecordHeaders(org.apache.kafka.common.header.internals.RecordHeaders) TaskMigratedException(org.apache.kafka.streams.errors.TaskMigratedException) Record(org.apache.kafka.streams.processor.api.Record) Collections.singletonMap(java.util.Collections.singletonMap) LinkedList(java.util.LinkedList) JmxReporter(org.apache.kafka.common.metrics.JmxReporter) Utils(org.apache.kafka.common.utils.Utils) EasyMock.anyObject(org.easymock.EasyMock.anyObject) Collections.emptyMap(java.util.Collections.emptyMap) TimeoutException(org.apache.kafka.common.errors.TimeoutException) Matchers.empty(org.hamcrest.Matchers.empty) Logger(org.slf4j.Logger) Collections.emptySet(java.util.Collections.emptySet) MockStateRestoreListener(org.apache.kafka.test.MockStateRestoreListener) Assert.assertNotNull(org.junit.Assert.assertNotNull) EasyMock.expect(org.easymock.EasyMock.expect) StoreBuilder(org.apache.kafka.streams.state.StoreBuilder) EasyMock.expectLastCall(org.easymock.EasyMock.expectLastCall) MockTimestampExtractor(org.apache.kafka.test.MockTimestampExtractor) InvalidOffsetException(org.apache.kafka.clients.consumer.InvalidOffsetException) StreamsTestUtils(org.apache.kafka.test.StreamsTestUtils) OffsetCheckpoint(org.apache.kafka.streams.state.internals.OffsetCheckpoint) EasyMock.verify(org.easymock.EasyMock.verify) Collections(java.util.Collections) Node(org.apache.kafka.common.Node) LogContext(org.apache.kafka.common.utils.LogContext) MockAdminClient(org.apache.kafka.clients.admin.MockAdminClient) KafkaMetric(org.apache.kafka.common.metrics.KafkaMetric) MetricName(org.apache.kafka.common.MetricName) ConsumerGroupMetadata(org.apache.kafka.clients.consumer.ConsumerGroupMetadata) AtomicLong(java.util.concurrent.atomic.AtomicLong) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Metric(org.apache.kafka.common.Metric) KafkaMetric(org.apache.kafka.common.metrics.KafkaMetric) EasyMock.anyObject(org.easymock.EasyMock.anyObject) StreamsMetricsImpl(org.apache.kafka.streams.processor.internals.metrics.StreamsMetricsImpl) MockTime(org.apache.kafka.common.utils.MockTime) Test(org.junit.Test)

Example 88 with KafkaMetric

use of org.apache.kafka.common.metrics.KafkaMetric in project kafka by apache.

the class StreamsMetricsImplTest method verifyMetric.

private void verifyMetric(final String name, final String description, final double valueToRecord1, final double valueToRecord2, final double expectedMetricValue) {
    final KafkaMetric metric = metrics.metric(new MetricName(name, group, description, tags));
    assertThat(metric, is(notNullValue()));
    assertThat(metric.metricName().description(), equalTo(description));
    sensor.record(valueToRecord1, time.milliseconds());
    sensor.record(valueToRecord2, time.milliseconds());
    assertThat(metric.measurable().measure(new MetricConfig(), time.milliseconds()), equalTo(expectedMetricValue));
}
Also used : MetricConfig(org.apache.kafka.common.metrics.MetricConfig) MetricName(org.apache.kafka.common.MetricName) KafkaMetric(org.apache.kafka.common.metrics.KafkaMetric)

Example 89 with KafkaMetric

use of org.apache.kafka.common.metrics.KafkaMetric in project kafka by apache.

the class MeteredKeyValueStoreTest method shouldPutIfAbsentAndRecordPutIfAbsentMetric.

@Test
public void shouldPutIfAbsentAndRecordPutIfAbsentMetric() {
    expect(inner.putIfAbsent(eq(KEY_BYTES), aryEq(VALUE_BYTES))).andReturn(null);
    init();
    metered.putIfAbsent(KEY, VALUE);
    final KafkaMetric metric = metric("put-if-absent-rate");
    assertTrue((Double) metric.metricValue() > 0);
    verify(inner);
}
Also used : KafkaMetric(org.apache.kafka.common.metrics.KafkaMetric) Test(org.junit.Test)

Example 90 with KafkaMetric

use of org.apache.kafka.common.metrics.KafkaMetric in project kafka by apache.

the class MeteredKeyValueStoreTest method shouldPutAllToInnerStoreAndRecordPutAllMetric.

@SuppressWarnings("unchecked")
@Test
public void shouldPutAllToInnerStoreAndRecordPutAllMetric() {
    inner.putAll(anyObject(List.class));
    expectLastCall();
    init();
    metered.putAll(Collections.singletonList(KeyValue.pair(KEY, VALUE)));
    final KafkaMetric metric = metric("put-all-rate");
    assertTrue((Double) metric.metricValue() > 0);
    verify(inner);
}
Also used : List(java.util.List) KafkaMetric(org.apache.kafka.common.metrics.KafkaMetric) Test(org.junit.Test)

Aggregations

KafkaMetric (org.apache.kafka.common.metrics.KafkaMetric)129 Test (org.junit.Test)84 MetricName (org.apache.kafka.common.MetricName)59 HashMap (java.util.HashMap)30 LinkedHashMap (java.util.LinkedHashMap)24 Test (org.junit.jupiter.api.Test)23 Map (java.util.Map)18 MetricConfig (org.apache.kafka.common.metrics.MetricConfig)16 Metric (org.apache.kafka.common.Metric)15 MemoryRecordsBuilder (org.apache.kafka.common.record.MemoryRecordsBuilder)14 ConsumerRecord (org.apache.kafka.clients.consumer.ConsumerRecord)13 MeterRegistry (io.micrometer.core.instrument.MeterRegistry)12 SimpleMeterRegistry (io.micrometer.core.instrument.simple.SimpleMeterRegistry)12 Value (org.apache.kafka.common.metrics.stats.Value)12 Windowed (org.apache.kafka.streams.kstream.Windowed)12 Sensor (org.apache.kafka.common.metrics.Sensor)11 TopicPartition (org.apache.kafka.common.TopicPartition)10 Metrics (org.apache.kafka.common.metrics.Metrics)10 List (java.util.List)8 Cluster (org.apache.kafka.common.Cluster)8