[SDC] Add kafka native messaging
[sdc.git] / catalog-be / src / main / java / org / openecomp / sdc / be / components / kafka / SdcKafkaConsumer.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * SDC
4  * ================================================================================
5  * Copyright (C) 2022 Nordix Foundation. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20 package org.openecomp.sdc.be.components.kafka;
21
22 import com.google.common.annotations.VisibleForTesting;
23 import java.time.Duration;
24 import java.util.ArrayList;
25 import java.util.Collections;
26 import java.util.List;
27 import java.util.Properties;
28 import java.util.UUID;
29 import org.apache.kafka.clients.CommonClientConfigs;
30 import org.apache.kafka.clients.consumer.ConsumerConfig;
31 import org.apache.kafka.clients.consumer.ConsumerRecord;
32 import org.apache.kafka.clients.consumer.ConsumerRecords;
33 import org.apache.kafka.clients.consumer.KafkaConsumer;
34 import org.apache.kafka.common.KafkaException;
35 import org.apache.kafka.common.config.SaslConfigs;
36 import org.openecomp.sdc.be.config.DistributionEngineConfiguration;
37 import org.openecomp.sdc.common.log.wrappers.Logger;
38
39 /**
40  * Utility class that provides a KafkaConsumer to communicate with a kafka cluster
41  */
42 public class SdcKafkaConsumer {
43
44     private static final Logger log = Logger.getLogger(SdcKafkaConsumer.class.getName());
45     private final DistributionEngineConfiguration deConfiguration;
46     private KafkaConsumer<String, String> kafkaConsumer;
47
48     /**
49      * Constructor setting up the KafkaConsumer from a predefined set of configurations
50      */
51     public SdcKafkaConsumer(DistributionEngineConfiguration deConfiguration){
52         log.info("Create SdcKafkaConsumer via constructor");
53         Properties properties = new Properties();
54         this.deConfiguration = deConfiguration;
55
56         properties.put(ConsumerConfig.CLIENT_ID_CONFIG, deConfiguration.getDistributionStatusTopic().getConsumerId()+ "-consumer-" + UUID.randomUUID());
57         properties.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringDeserializer");
58         properties.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG,  "org.apache.kafka.common.serialization.StringDeserializer");
59         properties.put(ConsumerConfig.GROUP_ID_CONFIG, deConfiguration.getDistributionStatusTopic().getConsumerGroup());
60         properties.put(CommonClientConfigs.BOOTSTRAP_SERVERS_CONFIG, deConfiguration.getKafkaBootStrapServers());
61         properties.put(CommonClientConfigs.SECURITY_PROTOCOL_CONFIG, "SASL_PLAINTEXT");
62         properties.put(ConsumerConfig.ALLOW_AUTO_CREATE_TOPICS_CONFIG, false);
63         properties.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "latest");
64         properties.put(SaslConfigs.SASL_MECHANISM, "SCRAM-SHA-512");
65
66         properties.put(SaslConfigs.SASL_JAAS_CONFIG, getKafkaSaslJaasConfig());
67         kafkaConsumer = new KafkaConsumer<>(properties);
68     }
69
70     /**
71      *
72      * @param kafkaConsumer a kafkaConsumer to use within the class
73      * @param deConfiguration - Configuration to pass into the class
74      */
75     @VisibleForTesting
76     SdcKafkaConsumer(KafkaConsumer kafkaConsumer, DistributionEngineConfiguration deConfiguration){
77         this.deConfiguration = deConfiguration;
78         this.kafkaConsumer = kafkaConsumer;
79     }
80
81     /**
82      *
83      * @return the Sasl Jass Config
84      */
85     private String getKafkaSaslJaasConfig() {
86         String saslJaasConfFromEnv = System.getenv("SASL_JAAS_CONFIG");
87         if(saslJaasConfFromEnv != null) {
88             return saslJaasConfFromEnv;
89         } else {
90             throw new KafkaException("sasl.jaas.config not set for Kafka Consumer");
91         }
92     }
93
94     /**
95      *
96      * @param topic Topic in which to subscribe
97      */
98     public void subscribe(String topic) throws KafkaException {
99         if (!kafkaConsumer.subscription().contains(topic)) {
100             kafkaConsumer.subscribe(Collections.singleton(topic));
101         }
102     }
103
104     /**
105      *
106      * @return The list of messages for a specified topic, returned from the poll
107      */
108     public List<String> poll(String topicName) throws KafkaException {
109         log.info("SdcKafkaConsumer - polling for messages from Topic: {}", topicName);
110         List<String> msgs = new ArrayList<>();
111         ConsumerRecords<String, String> consumerRecordsForSpecificTopic = kafkaConsumer.poll(Duration.ofSeconds(deConfiguration.getDistributionStatusTopic().getPollingIntervalSec()));
112         for(ConsumerRecord<String, String> rec : consumerRecordsForSpecificTopic){
113             msgs.add(rec.value());
114         }
115         return msgs;
116     }
117 }