8de1f05be3abd13a3d50f752fd384461cbbd5829
[ccsdk/cds.git] / ms / blueprintsprocessor / modules / commons / message-lib / src / main / kotlin / org / onap / ccsdk / cds / blueprintsprocessor / message / service / KafkaMessageProducerService.kt
1 /*
2  *  Copyright © 2019 IBM.
3  *  Modifications Copyright © 2018-2019 AT&T 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 org.apache.commons.lang.builder.ToStringBuilder
22 import org.apache.kafka.clients.producer.Callback
23 import org.apache.kafka.clients.producer.KafkaProducer
24 import org.apache.kafka.clients.producer.ProducerRecord
25 import org.apache.kafka.common.header.internals.RecordHeader
26 import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.ExecutionServiceOutput
27 import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.Status
28 import org.onap.ccsdk.cds.blueprintsprocessor.message.MessageProducerProperties
29 import org.onap.ccsdk.cds.controllerblueprints.core.asJsonPrimitive
30 import org.onap.ccsdk.cds.controllerblueprints.core.asJsonString
31 import org.onap.ccsdk.cds.controllerblueprints.core.defaultToUUID
32 import org.slf4j.LoggerFactory
33 import java.nio.charset.Charset
34
35 class KafkaMessageProducerService(
36     private val messageProducerProperties: MessageProducerProperties
37 ) :
38     BlueprintMessageProducerService {
39
40     private val log = LoggerFactory.getLogger(KafkaMessageProducerService::class.java)!!
41
42     private var kafkaProducer: KafkaProducer<String, ByteArray>? = null
43
44     private val messageLoggerService = MessageLoggerService()
45
46     companion object {
47         const val MAX_ERR_MSG_LEN = 128
48     }
49
50     override suspend fun sendMessageNB(message: Any): Boolean {
51         checkNotNull(messageProducerProperties.topic) { "default topic is not configured" }
52         return sendMessageNB(messageProducerProperties.topic!!, message)
53     }
54
55     override suspend fun sendMessageNB(message: Any, headers: MutableMap<String, String>?): Boolean {
56         checkNotNull(messageProducerProperties.topic) { "default topic is not configured" }
57         return sendMessageNB(messageProducerProperties.topic!!, message, headers)
58     }
59
60     override suspend fun sendMessageNB(
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, defaultToUUID(), 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             if (exception == null) log.trace("message published to(${metadata.topic()}), offset(${metadata.offset()}), headers :$headers")
83             else log.error("ERROR : ${exception.message}")
84         }
85         messageTemplate().send(record, callback)
86         return true
87     }
88
89     fun messageTemplate(additionalConfig: Map<String, ByteArray>? = null): KafkaProducer<String, ByteArray> {
90         log.trace("Producer client properties : ${ToStringBuilder.reflectionToString(messageProducerProperties)}")
91         val configProps = messageProducerProperties.getConfig()
92
93         /** Add additional Properties */
94         if (additionalConfig != null)
95             configProps.putAll(additionalConfig)
96
97         if (kafkaProducer == null)
98             kafkaProducer = KafkaProducer(configProps)
99
100         return kafkaProducer!!
101     }
102
103     /**
104      * Truncation of BP responses
105      */
106     private fun truncateResponse(executionServiceOutput: ExecutionServiceOutput): ExecutionServiceOutput {
107         /** Truncation of error messages */
108         var truncErrMsg = executionServiceOutput.status.errorMessage
109         if (truncErrMsg != null && truncErrMsg.length > MAX_ERR_MSG_LEN) {
110             truncErrMsg = "${truncErrMsg.substring(0,MAX_ERR_MSG_LEN)}" +
111                     " [...]. Check Blueprint Processor logs for more information."
112         }
113         /** Truncation for Command Executor responses */
114         var truncPayload = executionServiceOutput.payload.deepCopy()
115         val workflowName = executionServiceOutput.actionIdentifiers.actionName
116         if (truncPayload.path("$workflowName-response").has("execute-command-logs")) {
117             var cmdExecLogNode = truncPayload.path("$workflowName-response") as ObjectNode
118             cmdExecLogNode.replace("execute-command-logs", "Check Command Executor logs for more information.".asJsonPrimitive())
119         }
120         return ExecutionServiceOutput().apply {
121             correlationUUID = executionServiceOutput.correlationUUID
122             commonHeader = executionServiceOutput.commonHeader
123             actionIdentifiers = executionServiceOutput.actionIdentifiers
124             status = Status().apply {
125                 code = executionServiceOutput.status.code
126                 eventType = executionServiceOutput.status.eventType
127                 timestamp = executionServiceOutput.status.timestamp
128                 errorMessage = truncErrMsg
129                 message = executionServiceOutput.status.message
130             }
131             payload = truncPayload
132             stepData = executionServiceOutput.stepData
133         }
134     }
135 }