Merge "Kafka Back pressure configuration"
[ccsdk/cds.git] / ms / blueprintsprocessor / modules / commons / message-lib / src / main / kotlin / org / onap / ccsdk / cds / blueprintsprocessor / message / service / KafkaBasicAuthMessageConsumerService.kt
1 /*
2  *  Copyright © 2019 IBM.
3  *
4  *  Licensed under the Apache License, Version 2.0 (the "License");
5  *  you may not use this file except in compliance with the License.
6  *  You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  *  Unless required by applicable law or agreed to in writing, software
11  *  distributed under the License is distributed on an "AS IS" BASIS,
12  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  *  See the License for the specific language governing permissions and
14  *  limitations under the License.
15  */
16
17 package org.onap.ccsdk.cds.blueprintsprocessor.message.service
18
19 import kotlinx.coroutines.channels.Channel
20 import kotlinx.coroutines.delay
21 import kotlinx.coroutines.launch
22 import kotlinx.coroutines.runBlocking
23 import org.apache.kafka.clients.CommonClientConfigs
24 import org.apache.kafka.clients.consumer.Consumer
25 import org.apache.kafka.clients.consumer.ConsumerConfig
26 import org.apache.kafka.clients.consumer.KafkaConsumer
27 import org.apache.kafka.common.serialization.StringDeserializer
28 import org.onap.ccsdk.cds.blueprintsprocessor.message.KafkaBasicAuthMessageConsumerProperties
29 import org.onap.ccsdk.cds.controllerblueprints.core.logger
30 import java.time.Duration
31 import kotlin.concurrent.thread
32
33 class KafkaBasicAuthMessageConsumerService(
34         private val messageConsumerProperties: KafkaBasicAuthMessageConsumerProperties)
35     : BlueprintMessageConsumerService {
36
37     private val channel = Channel<String>()
38     private var kafkaConsumer: Consumer<String, String>? = null
39     val log = logger(KafkaBasicAuthMessageConsumerService::class)
40
41     @Volatile
42     var keepGoing = true
43
44     fun kafkaConsumer(additionalConfig: Map<String, Any>? = null): Consumer<String, String> {
45         val configProperties = hashMapOf<String, Any>()
46         configProperties[CommonClientConfigs.BOOTSTRAP_SERVERS_CONFIG] = messageConsumerProperties.bootstrapServers
47         configProperties[ConsumerConfig.GROUP_ID_CONFIG] = messageConsumerProperties.groupId
48         configProperties[ConsumerConfig.AUTO_OFFSET_RESET_CONFIG] = "latest"
49         configProperties[ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG] = StringDeserializer::class.java
50         configProperties[ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG] = StringDeserializer::class.java
51         if (messageConsumerProperties.clientId != null) {
52             configProperties[ConsumerConfig.CLIENT_ID_CONFIG] = messageConsumerProperties.clientId!!
53         }
54         /** To handle Back pressure, Get only configured record for processing */
55         if (messageConsumerProperties.pollRecords > 0) {
56             configProperties[ConsumerConfig.MAX_POLL_RECORDS_CONFIG] = messageConsumerProperties.pollRecords
57         }
58         // TODO("Security Implementation based on type")
59         /** add or override already set properties */
60         additionalConfig?.let { configProperties.putAll(it) }
61         /** Create Kafka consumer */
62         return KafkaConsumer(configProperties)
63     }
64
65     override suspend fun subscribe(additionalConfig: Map<String, Any>?): Channel<String> {
66         /** get to topic names */
67         val consumerTopic = messageConsumerProperties.topic?.split(",")?.map { it.trim() }
68         check(!consumerTopic.isNullOrEmpty()) { "couldn't get topic information" }
69         return subscribe(consumerTopic, additionalConfig)
70     }
71
72
73     override suspend fun subscribe(consumerTopic: List<String>, additionalConfig: Map<String, Any>?): Channel<String> {
74         /** Create Kafka consumer */
75         kafkaConsumer = kafkaConsumer(additionalConfig)
76
77         checkNotNull(kafkaConsumer) {
78             "failed to create kafka consumer for " +
79                     "server(${messageConsumerProperties.bootstrapServers})'s " +
80                     "topics(${messageConsumerProperties.bootstrapServers})"
81         }
82
83         kafkaConsumer!!.subscribe(consumerTopic)
84         log.info("Successfully consumed topic($consumerTopic)")
85
86         thread(start = true, name = "KafkaConsumer") {
87             keepGoing = true
88             kafkaConsumer!!.use { kc ->
89                 while (keepGoing) {
90                     val consumerRecords = kc.poll(Duration.ofMillis(messageConsumerProperties.pollMillSec))
91                     log.info("Consumed Records : ${consumerRecords.count()}")
92                     runBlocking {
93                         consumerRecords?.forEach { consumerRecord ->
94                             /** execute the command block */
95                             consumerRecord.value()?.let {
96                                 launch {
97                                     if (!channel.isClosedForSend) {
98                                         channel.send(it)
99                                     } else {
100                                         log.error("Channel is closed to receive message")
101                                     }
102                                 }
103                             }
104                         }
105                     }
106                 }
107                 log.info("message listener shutting down.....")
108             }
109         }
110         return channel
111     }
112
113     override suspend fun shutDown() {
114         /** stop the polling loop */
115         keepGoing = false
116         /** Close the Channel */
117         channel.cancel()
118         /** TO shutdown gracefully, need to wait for the maximum poll time */
119         delay(messageConsumerProperties.pollMillSec)
120     }
121 }