d40067f4ef429f38f502fb0aab4c2c64303782ff
[ccsdk/cds.git] /
1 /*
2  *  Copyright © 2019 IBM.
3  *  Modifications Copyright © 2018-2021 AT&T, Bell Canada Intellectual Property.
4  *
5  *  Licensed under the Apache License, Version 2.0 (the "License");
6  *  you may not use this file except in compliance with the License.
7  *  You may obtain a copy of the License at
8  *
9  *      http://www.apache.org/licenses/LICENSE-2.0
10  *
11  *  Unless required by applicable law or agreed to in writing, software
12  *  distributed under the License is distributed on an "AS IS" BASIS,
13  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  *  See the License for the specific language governing permissions and
15  *  limitations under the License.
16  */
17
18 package org.onap.ccsdk.cds.blueprintsprocessor.message.service
19
20 import com.fasterxml.jackson.databind.node.ObjectNode
21 import io.micrometer.core.instrument.MeterRegistry
22 import org.apache.commons.lang.builder.ToStringBuilder
23 import org.apache.kafka.clients.producer.Callback
24 import org.apache.kafka.clients.producer.KafkaProducer
25 import org.apache.kafka.clients.producer.ProducerRecord
26 import org.apache.kafka.common.header.internals.RecordHeader
27 import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.ExecutionServiceOutput
28 import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.Status
29 import org.onap.ccsdk.cds.blueprintsprocessor.message.BlueprintMessageMetricConstants
30 import org.onap.ccsdk.cds.blueprintsprocessor.message.MessageProducerProperties
31 import org.onap.ccsdk.cds.blueprintsprocessor.message.utils.BlueprintMessageUtils
32 import org.onap.ccsdk.cds.controllerblueprints.core.asJsonPrimitive
33 import org.onap.ccsdk.cds.controllerblueprints.core.asJsonString
34 import org.slf4j.LoggerFactory
35 import java.nio.charset.Charset
36
37 class KafkaMessageProducerService(
38     private val messageProducerProperties: MessageProducerProperties,
39     private val meterRegistry: MeterRegistry
40 ) :
41     BlueprintMessageProducerService {
42
43     private val log = LoggerFactory.getLogger(KafkaMessageProducerService::class.java)!!
44
45     private var kafkaProducer: KafkaProducer<String, ByteArray>? = null
46
47     private val messageLoggerService = MessageLoggerService()
48
49     companion object {
50
51         const val MAX_ERR_MSG_LEN = 128
52     }
53
54     override suspend fun sendMessageNB(key: String, message: Any, headers: MutableMap<String, String>?): Boolean {
55         checkNotNull(messageProducerProperties.topic) { "default topic is not configured" }
56         return sendMessageNB(key, messageProducerProperties.topic!!, message, headers)
57     }
58
59     override suspend fun sendMessageNB(
60         key: String,
61         topic: String,
62         message: Any,
63         headers: MutableMap<String, String>?
64     ): Boolean {
65         var clonedMessage = message
66         if (clonedMessage is ExecutionServiceOutput) {
67             clonedMessage = truncateResponse(clonedMessage)
68         }
69
70         val byteArrayMessage = when (clonedMessage) {
71             is String -> clonedMessage.toByteArray(Charset.defaultCharset())
72             else -> clonedMessage.asJsonString().toByteArray(Charset.defaultCharset())
73         }
74
75         val record = ProducerRecord<String, ByteArray>(topic, key, byteArrayMessage)
76         val recordHeaders = record.headers()
77         messageLoggerService.messageProducing(recordHeaders)
78         headers?.let {
79             headers.forEach { (key, value) -> recordHeaders.add(RecordHeader(key, value.toByteArray())) }
80         }
81         val callback = Callback { metadata, exception ->
82             meterRegistry.counter(
83                 BlueprintMessageMetricConstants.KAFKA_PRODUCED_MESSAGES_COUNTER,
84                 BlueprintMessageUtils.kafkaMetricTag(topic)
85             ).increment()
86             if (exception != null) {
87                 meterRegistry.counter(
88                     BlueprintMessageMetricConstants.KAFKA_PRODUCED_MESSAGES_ERROR_COUNTER,
89                     BlueprintMessageUtils.kafkaMetricTag(topic)
90                 ).increment()
91                 log.error("Couldn't publish ${clonedMessage::class.simpleName} ${BlueprintMessageUtils.getMessageLogData(clonedMessage)}.", exception)
92             } else {
93                 log.info(
94                     "${clonedMessage::class.simpleName} published : topic(${metadata.topic()}) " +
95                         "partition(${metadata.partition()}) " +
96                         "offset(${metadata.offset()}) ${BlueprintMessageUtils.getMessageLogData(clonedMessage)}."
97                 )
98             }
99         }
100         messageTemplate().send(record, callback)
101         return true
102     }
103
104     fun messageTemplate(additionalConfig: Map<String, ByteArray>? = null): KafkaProducer<String, ByteArray> {
105         log.trace("Producer client properties : ${ToStringBuilder.reflectionToString(messageProducerProperties)}")
106         val configProps = messageProducerProperties.getConfig()
107         /** Add additional Properties */
108         if (additionalConfig != null)
109             configProps.putAll(additionalConfig)
110
111         if (kafkaProducer == null)
112             kafkaProducer = KafkaProducer(configProps)
113
114         return kafkaProducer!!
115     }
116
117     /**
118      * Truncation of BP responses
119      */
120     private fun truncateResponse(executionServiceOutput: ExecutionServiceOutput): ExecutionServiceOutput {
121         /** Truncation of error messages */
122         var truncErrMsg = executionServiceOutput.status.errorMessage
123         if (truncErrMsg != null && truncErrMsg.length > MAX_ERR_MSG_LEN) {
124             truncErrMsg = truncErrMsg.substring(0, MAX_ERR_MSG_LEN) +
125                 " [...]. Check Blueprint Processor logs for more information."
126         }
127         /** Truncation for Command Executor responses */
128         var truncPayload = executionServiceOutput.payload.deepCopy()
129         val workflowName = executionServiceOutput.actionIdentifiers.actionName
130         if (truncPayload.path("$workflowName-response").has("execute-command-logs")) {
131             var cmdExecLogNode = truncPayload.path("$workflowName-response") as ObjectNode
132             cmdExecLogNode.replace("execute-command-logs", "Check Command Executor logs for more information.".asJsonPrimitive())
133         }
134         return ExecutionServiceOutput().apply {
135             correlationUUID = executionServiceOutput.correlationUUID
136             commonHeader = executionServiceOutput.commonHeader
137             actionIdentifiers = executionServiceOutput.actionIdentifiers
138             status = Status().apply {
139                 code = executionServiceOutput.status.code
140                 eventType = executionServiceOutput.status.eventType
141                 timestamp = executionServiceOutput.status.timestamp
142                 errorMessage = truncErrMsg
143                 message = executionServiceOutput.status.message
144             }
145             payload = truncPayload
146             stepData = executionServiceOutput.stepData
147         }
148     }
149 }