Search in sources :

Example 31 with Metric

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

the class KTableSuppressProcessorMetricsTest method shouldRecordMetricsWithBuiltInMetricsVersionLatest.

@Test
public void shouldRecordMetricsWithBuiltInMetricsVersionLatest() {
    final String storeName = "test-store";
    final StateStore buffer = new InMemoryTimeOrderedKeyValueBuffer.Builder<>(storeName, Serdes.String(), Serdes.Long()).withLoggingDisabled().build();
    final KTableImpl<String, ?, Long> mock = EasyMock.mock(KTableImpl.class);
    final Processor<String, Change<Long>, String, Change<Long>> processor = new KTableSuppressProcessorSupplier<>((SuppressedInternal<String>) Suppressed.<String>untilTimeLimit(Duration.ofDays(100), maxRecords(1)), storeName, mock).get();
    streamsConfig.setProperty(StreamsConfig.BUILT_IN_METRICS_VERSION_CONFIG, StreamsConfig.METRICS_LATEST);
    final MockInternalNewProcessorContext<String, Change<Long>> context = new MockInternalNewProcessorContext<>(streamsConfig, TASK_ID, TestUtils.tempDirectory());
    final Time time = new SystemTime();
    context.setCurrentNode(new ProcessorNode("testNode"));
    context.setSystemTimeMs(time.milliseconds());
    buffer.init((StateStoreContext) context, buffer);
    processor.init(context);
    final long timestamp = 100L;
    context.setRecordMetadata("", 0, 0L);
    context.setTimestamp(timestamp);
    final String key = "longKey";
    final Change<Long> value = new Change<>(null, ARBITRARY_LONG);
    processor.process(new Record<>(key, value, timestamp));
    final MetricName evictionRateMetric = evictionRateMetricLatest;
    final MetricName evictionTotalMetric = evictionTotalMetricLatest;
    final MetricName bufferSizeAvgMetric = bufferSizeAvgMetricLatest;
    final MetricName bufferSizeMaxMetric = bufferSizeMaxMetricLatest;
    final MetricName bufferCountAvgMetric = bufferCountAvgMetricLatest;
    final MetricName bufferCountMaxMetric = bufferCountMaxMetricLatest;
    {
        final Map<MetricName, ? extends Metric> metrics = context.metrics().metrics();
        verifyMetric(metrics, evictionRateMetric, is(0.0));
        verifyMetric(metrics, evictionTotalMetric, is(0.0));
        verifyMetric(metrics, bufferSizeAvgMetric, is(21.5));
        verifyMetric(metrics, bufferSizeMaxMetric, is(43.0));
        verifyMetric(metrics, bufferCountAvgMetric, is(0.5));
        verifyMetric(metrics, bufferCountMaxMetric, is(1.0));
    }
    context.setRecordMetadata("", 0, 1L);
    context.setTimestamp(timestamp + 1);
    processor.process(new Record<>("key", value, timestamp + 1));
    {
        final Map<MetricName, ? extends Metric> metrics = context.metrics().metrics();
        verifyMetric(metrics, evictionRateMetric, greaterThan(0.0));
        verifyMetric(metrics, evictionTotalMetric, is(1.0));
        verifyMetric(metrics, bufferSizeAvgMetric, is(41.0));
        verifyMetric(metrics, bufferSizeMaxMetric, is(82.0));
        verifyMetric(metrics, bufferCountAvgMetric, is(1.0));
        verifyMetric(metrics, bufferCountMaxMetric, is(2.0));
    }
}
Also used : StateStore(org.apache.kafka.streams.processor.StateStore) Time(org.apache.kafka.common.utils.Time) SystemTime(org.apache.kafka.common.utils.SystemTime) Change(org.apache.kafka.streams.kstream.internals.Change) MetricName(org.apache.kafka.common.MetricName) ProcessorNode(org.apache.kafka.streams.processor.internals.ProcessorNode) MockInternalNewProcessorContext(org.apache.kafka.test.MockInternalNewProcessorContext) Metric(org.apache.kafka.common.Metric) Utils.mkMap(org.apache.kafka.common.utils.Utils.mkMap) Map(java.util.Map) SystemTime(org.apache.kafka.common.utils.SystemTime) Test(org.junit.Test)

Example 32 with Metric

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

the class KafkaProducerTest method getMetricValue.

private static Double getMetricValue(final KafkaProducer<?, ?> producer, final String name) {
    Metrics metrics = producer.metrics;
    Metric metric = metrics.metric(metrics.metricName(name, "producer-metrics"));
    return (Double) metric.metricValue();
}
Also used : Metrics(org.apache.kafka.common.metrics.Metrics) Metric(org.apache.kafka.common.Metric)

Example 33 with Metric

use of org.apache.kafka.common.Metric 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 34 with Metric

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

the class AbstractRocksDBSegmentedBytesStoreTest method shouldLogAndMeasureExpiredRecords.

@Test
public void shouldLogAndMeasureExpiredRecords() {
    final Properties streamsConfig = StreamsTestUtils.getStreamsConfig();
    final AbstractRocksDBSegmentedBytesStore<S> bytesStore = getBytesStore();
    final InternalMockProcessorContext context = new InternalMockProcessorContext(TestUtils.tempDirectory(), new StreamsConfig(streamsConfig));
    final Time time = new SystemTime();
    context.setSystemTimeMs(time.milliseconds());
    bytesStore.init((StateStoreContext) context, bytesStore);
    try (final LogCaptureAppender appender = LogCaptureAppender.createAndRegister()) {
        // write a record to advance stream time, with a high enough timestamp
        // that the subsequent record in windows[0] will already be expired.
        bytesStore.put(serializeKey(new Windowed<>("dummy", nextSegmentWindow)), serializeValue(0));
        final Bytes key = serializeKey(new Windowed<>("a", windows[0]));
        final byte[] value = serializeValue(5);
        bytesStore.put(key, value);
        final List<String> messages = appender.getMessages();
        assertThat(messages, hasItem("Skipping record for expired segment."));
    }
    final Map<MetricName, ? extends Metric> metrics = context.metrics().metrics();
    final String threadId = Thread.currentThread().getName();
    final Metric dropTotal;
    final Metric dropRate;
    dropTotal = metrics.get(new MetricName("dropped-records-total", "stream-task-metrics", "", mkMap(mkEntry("thread-id", threadId), mkEntry("task-id", "0_0"))));
    dropRate = metrics.get(new MetricName("dropped-records-rate", "stream-task-metrics", "", mkMap(mkEntry("thread-id", threadId), mkEntry("task-id", "0_0"))));
    assertEquals(1.0, dropTotal.metricValue());
    assertNotEquals(0.0, dropRate.metricValue());
    bytesStore.close();
}
Also used : MockTime(org.apache.kafka.common.utils.MockTime) Time(org.apache.kafka.common.utils.Time) SystemTime(org.apache.kafka.common.utils.SystemTime) Properties(java.util.Properties) Windowed(org.apache.kafka.streams.kstream.Windowed) Bytes(org.apache.kafka.common.utils.Bytes) MetricName(org.apache.kafka.common.MetricName) LogCaptureAppender(org.apache.kafka.streams.processor.internals.testutil.LogCaptureAppender) Metric(org.apache.kafka.common.Metric) InternalMockProcessorContext(org.apache.kafka.test.InternalMockProcessorContext) StreamsConfig(org.apache.kafka.streams.StreamsConfig) SystemTime(org.apache.kafka.common.utils.SystemTime) Test(org.junit.Test)

Example 35 with Metric

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

the class AbstractSessionBytesStoreTest method shouldLogAndMeasureExpiredRecords.

@Test
public void shouldLogAndMeasureExpiredRecords() {
    final Properties streamsConfig = StreamsTestUtils.getStreamsConfig();
    final SessionStore<String, Long> sessionStore = buildSessionStore(RETENTION_PERIOD, Serdes.String(), Serdes.Long());
    final InternalMockProcessorContext context = new InternalMockProcessorContext(TestUtils.tempDirectory(), new StreamsConfig(streamsConfig), recordCollector);
    final Time time = new SystemTime();
    context.setTime(1L);
    context.setSystemTimeMs(time.milliseconds());
    sessionStore.init((StateStoreContext) context, sessionStore);
    try (final LogCaptureAppender appender = LogCaptureAppender.createAndRegister()) {
        // Advance stream time by inserting record with large enough timestamp that records with timestamp 0 are expired
        // Note that rocksdb will only expire segments at a time (where segment interval = 60,000 for this retention period)
        sessionStore.put(new Windowed<>("initial record", new SessionWindow(0, 2 * SEGMENT_INTERVAL)), 0L);
        // Try inserting a record with timestamp 0 -- should be dropped
        sessionStore.put(new Windowed<>("late record", new SessionWindow(0, 0)), 0L);
        sessionStore.put(new Windowed<>("another on-time record", new SessionWindow(0, 2 * SEGMENT_INTERVAL)), 0L);
        final List<String> messages = appender.getMessages();
        assertThat(messages, hasItem("Skipping record for expired segment."));
    }
    final Map<MetricName, ? extends Metric> metrics = context.metrics().metrics();
    final String threadId = Thread.currentThread().getName();
    final Metric dropTotal;
    final Metric dropRate;
    dropTotal = metrics.get(new MetricName("dropped-records-total", "stream-task-metrics", "", mkMap(mkEntry("thread-id", threadId), mkEntry("task-id", "0_0"))));
    dropRate = metrics.get(new MetricName("dropped-records-rate", "stream-task-metrics", "", mkMap(mkEntry("thread-id", threadId), mkEntry("task-id", "0_0"))));
    assertEquals(1.0, dropTotal.metricValue());
    assertNotEquals(0.0, dropRate.metricValue());
    sessionStore.close();
}
Also used : Time(org.apache.kafka.common.utils.Time) SystemTime(org.apache.kafka.common.utils.SystemTime) Properties(java.util.Properties) MetricName(org.apache.kafka.common.MetricName) LogCaptureAppender(org.apache.kafka.streams.processor.internals.testutil.LogCaptureAppender) Metric(org.apache.kafka.common.Metric) SessionWindow(org.apache.kafka.streams.kstream.internals.SessionWindow) InternalMockProcessorContext(org.apache.kafka.test.InternalMockProcessorContext) StreamsConfig(org.apache.kafka.streams.StreamsConfig) SystemTime(org.apache.kafka.common.utils.SystemTime) Test(org.junit.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