f47a66d0301f9781713e38208ec069457748461b
[dcaegen2/collectors/hv-ves.git] /
1 /*
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
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
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=========================================================
19  */
20 package org.onap.dcae.collectors.veshv.kafkaconsumer.impl
21
22
23 import kotlinx.coroutines.CoroutineDispatcher
24 import kotlinx.coroutines.Dispatchers
25 import kotlinx.coroutines.GlobalScope
26 import kotlinx.coroutines.Job
27 import kotlinx.coroutines.delay
28 import kotlinx.coroutines.isActive
29 import kotlinx.coroutines.launch
30 import org.apache.kafka.clients.consumer.ConsumerRecord
31 import org.apache.kafka.clients.consumer.KafkaConsumer
32 import org.onap.dcae.collectors.veshv.kafkaconsumer.metrics.Metrics
33 import org.onap.dcae.collectors.veshv.utils.logging.Logger
34 import org.onap.ves.VesEventOuterClass
35 import java.time.Duration
36
37 internal class ProcessingKafkaConsumer (private val kafkaConsumer: KafkaConsumer<ByteArray, ByteArray>,
38                                         private val topics: Set<String>,
39                                         private val metrics: Metrics,
40                                         private val dispatcher: CoroutineDispatcher = Dispatchers.IO){
41
42     suspend fun start(updateInterval: Long = 500L, timeout: Duration): Job =
43             GlobalScope.launch(dispatcher){
44                 kafkaConsumer.subscribe(topics)
45                 while (isActive){
46                     kafkaConsumer.poll(timeout).forEach(::update)
47                     kafkaConsumer.commitSync()
48                     delay(updateInterval)
49                 }
50             }
51
52     private fun update(record: ConsumerRecord<ByteArray, ByteArray>) {
53         val vesEvent = VesEventOuterClass.VesEvent.parseFrom(record.value())
54         metrics.notifyMessageTravelTime(vesEvent.commonEventHeader.lastEpochMicrosec)
55     }
56 }