2 * ============LICENSE_START=======================================================
3 * dcaegen2-collectors-veshv
4 * ================================================================================
5 * Copyright (C) 2019 NOKIA
6 * ================================================================================
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ============LICENSE_END=========================================================
20 package org.onap.dcae.collectors.veshv.kafkaconsumer.impl
22 import kotlinx.coroutines.CoroutineDispatcher
23 import kotlinx.coroutines.Dispatchers
24 import kotlinx.coroutines.GlobalScope
25 import kotlinx.coroutines.Job
26 import kotlinx.coroutines.delay
27 import kotlinx.coroutines.isActive
28 import kotlinx.coroutines.launch
29 import org.apache.kafka.clients.consumer.KafkaConsumer
30 import org.apache.kafka.common.TopicPartition
31 import org.onap.dcae.collectors.veshv.kafkaconsumer.api.MetricsKafkaConsumer
32 import org.onap.dcae.collectors.veshv.kafkaconsumer.metrics.Metrics
33 import org.onap.dcae.collectors.veshv.utils.logging.Logger
34 import java.time.Duration
36 internal class OffsetKafkaConsumer(private val kafkaConsumer: KafkaConsumer<ByteArray, ByteArray>,
37 private val topics: Set<String>,
38 private val metrics: Metrics,
39 private val dispatcher: CoroutineDispatcher = Dispatchers.IO)
40 : MetricsKafkaConsumer{
42 override suspend fun start(updateInterval: Long, pollTimeout: Duration):Job =
43 GlobalScope.launch(dispatcher) {
44 kafkaConsumer.assign(topics.map { TopicPartition(it, 0) })
46 val topicPartitions = kafkaConsumer.assignment()
48 kafkaConsumer.endOffsets(topicPartitions)
49 .forEach { (topicPartition, offset) ->
50 update(topicPartition, offset)
52 kafkaConsumer.commitSync()
57 private fun update(topicPartition: TopicPartition, offset: Long) {
59 "Current consumer offset $offset for topic partition $topicPartition"
61 metrics.notifyOffsetChanged(offset, topicPartition)
65 private val logger = Logger(OffsetKafkaConsumer::class)