2 * Copyright © 2019 IBM.
3 * Modifications Copyright © 2018-2021 AT&T, Bell Canada Intellectual Property.
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
9 * http://www.apache.org/licenses/LICENSE-2.0
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.
18 package org.onap.ccsdk.cds.blueprintsprocessor.message.service
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
37 class KafkaMessageProducerService(
38 private val messageProducerProperties: MessageProducerProperties,
39 private val meterRegistry: MeterRegistry
41 BlueprintMessageProducerService {
43 private val log = LoggerFactory.getLogger(KafkaMessageProducerService::class.java)!!
45 private var kafkaProducer: KafkaProducer<String, ByteArray>? = null
47 private val messageLoggerService = MessageLoggerService()
51 const val MAX_ERR_MSG_LEN = 128
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)
59 override suspend fun sendMessageNB(
63 headers: MutableMap<String, String>?
65 var clonedMessage = message
66 if (clonedMessage is ExecutionServiceOutput) {
67 clonedMessage = truncateResponse(clonedMessage)
70 val byteArrayMessage = when (clonedMessage) {
71 is String -> clonedMessage.toByteArray(Charset.defaultCharset())
72 else -> clonedMessage.asJsonString().toByteArray(Charset.defaultCharset())
75 val record = ProducerRecord<String, ByteArray>(topic, key, byteArrayMessage)
76 val recordHeaders = record.headers()
77 messageLoggerService.messageProducing(recordHeaders)
79 headers.forEach { (key, value) -> recordHeaders.add(RecordHeader(key, value.toByteArray())) }
81 val callback = Callback { metadata, exception ->
82 meterRegistry.counter(
83 BlueprintMessageMetricConstants.KAFKA_PRODUCED_MESSAGES_COUNTER,
84 BlueprintMessageUtils.kafkaMetricTag(topic)
86 if (exception != null) {
87 meterRegistry.counter(
88 BlueprintMessageMetricConstants.KAFKA_PRODUCED_MESSAGES_ERROR_COUNTER,
89 BlueprintMessageUtils.kafkaMetricTag(topic)
91 log.error("Couldn't publish ${clonedMessage::class.simpleName} ${BlueprintMessageUtils.getMessageLogData(clonedMessage)}.", exception)
94 "${clonedMessage::class.simpleName} published : topic(${metadata.topic()}) " +
95 "partition(${metadata.partition()}) " +
96 "offset(${metadata.offset()}) ${BlueprintMessageUtils.getMessageLogData(clonedMessage)}."
100 messageTemplate().send(record, callback)
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)
111 if (kafkaProducer == null)
112 kafkaProducer = KafkaProducer(configProps)
114 return kafkaProducer!!
118 * Truncation of BP responses
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."
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())
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
145 payload = truncPayload
146 stepData = executionServiceOutput.stepData