8958d4f0cd8b33c14df1f08d641e70db4890f40b
[ccsdk/cds.git] /
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.ExecutionServiceInput
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.MessageProducerProperties
30 import org.onap.ccsdk.cds.controllerblueprints.core.asJsonPrimitive
31 import org.onap.ccsdk.cds.controllerblueprints.core.asJsonString
32 import org.onap.ccsdk.cds.controllerblueprints.core.defaultToUUID
33 import org.slf4j.LoggerFactory
34 import java.nio.charset.Charset
35
36 class KafkaMessageProducerService(
37     private val messageProducerProperties: MessageProducerProperties
38 ) :
39     BlueprintMessageProducerService {
40
41     private val log = LoggerFactory.getLogger(KafkaMessageProducerService::class.java)!!
42
43     private var kafkaProducer: KafkaProducer<String, ByteArray>? = null
44
45     private val messageLoggerService = MessageLoggerService()
46
47     companion object {
48         const val MAX_ERR_MSG_LEN = 128
49     }
50
51     override suspend fun sendMessageNB(message: Any): Boolean {
52         checkNotNull(messageProducerProperties.topic) { "default topic is not configured" }
53         return sendMessageNB(messageProducerProperties.topic!!, message)
54     }
55
56     override suspend fun sendMessageNB(message: Any, headers: MutableMap<String, String>?): Boolean {
57         checkNotNull(messageProducerProperties.topic) { "default topic is not configured" }
58         return sendMessageNB(messageProducerProperties.topic!!, message, headers)
59     }
60
61     override suspend fun sendMessageNB(
62         topic: String,
63         message: Any,
64         headers: MutableMap<String, String>?
65     ): Boolean {
66         var clonedMessage = message
67         if (clonedMessage is ExecutionServiceOutput) {
68             clonedMessage = truncateResponse(clonedMessage)
69         }
70
71         val byteArrayMessage = when (clonedMessage) {
72             is String -> clonedMessage.toByteArray(Charset.defaultCharset())
73             else -> clonedMessage.asJsonString().toByteArray(Charset.defaultCharset())
74         }
75
76         val record = ProducerRecord<String, ByteArray>(topic, defaultToUUID(), byteArrayMessage)
77         val recordHeaders = record.headers()
78         messageLoggerService.messageProducing(recordHeaders)
79         headers?.let {
80             headers.forEach { (key, value) -> recordHeaders.add(RecordHeader(key, value.toByteArray())) }
81         }
82         val callback = Callback { metadata, exception ->
83             if (exception != null)
84                 log.error("ERROR : ${exception.message}")
85             else {
86                 var logMessage = when (clonedMessage) {
87                     is ExecutionServiceInput ->
88                         "Request published to ${metadata.topic()} for CBA: ${clonedMessage.actionIdentifiers.blueprintName} version: ${clonedMessage.actionIdentifiers.blueprintVersion}"
89                     is ExecutionServiceOutput ->
90                         "Response published to ${metadata.topic()} for CBA: ${clonedMessage.actionIdentifiers.blueprintName} version: ${clonedMessage.actionIdentifiers.blueprintVersion}"
91                     else -> "Message published to(${metadata.topic()}), offset(${metadata.offset()}), headers :$headers"
92                 }
93                 log.info(logMessage)
94             }
95         }
96         messageTemplate().send(record, callback)
97         return true
98     }
99
100     fun messageTemplate(additionalConfig: Map<String, ByteArray>? = null): KafkaProducer<String, ByteArray> {
101         log.trace("Producer client properties : ${ToStringBuilder.reflectionToString(messageProducerProperties)}")
102         val configProps = messageProducerProperties.getConfig()
103
104         /** Add additional Properties */
105         if (additionalConfig != null)
106             configProps.putAll(additionalConfig)
107
108         if (kafkaProducer == null)
109             kafkaProducer = KafkaProducer(configProps)
110
111         return kafkaProducer!!
112     }
113
114     /**
115      * Truncation of BP responses
116      */
117     private fun truncateResponse(executionServiceOutput: ExecutionServiceOutput): ExecutionServiceOutput {
118         /** Truncation of error messages */
119         var truncErrMsg = executionServiceOutput.status.errorMessage
120         if (truncErrMsg != null && truncErrMsg.length > MAX_ERR_MSG_LEN) {
121             truncErrMsg = "${truncErrMsg.substring(0,MAX_ERR_MSG_LEN)}" +
122                     " [...]. Check Blueprint Processor logs for more information."
123         }
124         /** Truncation for Command Executor responses */
125         var truncPayload = executionServiceOutput.payload.deepCopy()
126         val workflowName = executionServiceOutput.actionIdentifiers.actionName
127         if (truncPayload.path("$workflowName-response").has("execute-command-logs")) {
128             var cmdExecLogNode = truncPayload.path("$workflowName-response") as ObjectNode
129             cmdExecLogNode.replace("execute-command-logs", "Check Command Executor logs for more information.".asJsonPrimitive())
130         }
131         return ExecutionServiceOutput().apply {
132             correlationUUID = executionServiceOutput.correlationUUID
133             commonHeader = executionServiceOutput.commonHeader
134             actionIdentifiers = executionServiceOutput.actionIdentifiers
135             status = Status().apply {
136                 code = executionServiceOutput.status.code
137                 eventType = executionServiceOutput.status.eventType
138                 timestamp = executionServiceOutput.status.timestamp
139                 errorMessage = truncErrMsg
140                 message = executionServiceOutput.status.message
141             }
142             payload = truncPayload
143             stepData = executionServiceOutput.stepData
144         }
145     }
146 }