04df4e1fbe4b17fd977e6399bada86216d386754
[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 static final String DEFAULT_SASL_MECHANISM = "SCRAM-SHA-512";
46
47     private final DistributionEngineConfiguration deConfiguration;
48     private KafkaConsumer<String, String> kafkaConsumer;
49
50     /**
51      * Constructor setting up the KafkaConsumer from a predefined set of configurations
52      */
53     public SdcKafkaConsumer(DistributionEngineConfiguration deConfiguration){
54         log.info("Create SdcKafkaConsumer via constructor");
55         Properties properties = new Properties();
56         this.deConfiguration = deConfiguration;
57
58         properties.put(ConsumerConfig.CLIENT_ID_CONFIG, deConfiguration.getDistributionStatusTopic().getConsumerId()+ "-consumer-" + UUID.randomUUID());
59         properties.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringDeserializer");
60         properties.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG,  "org.apache.kafka.common.serialization.StringDeserializer");
61         properties.put(ConsumerConfig.GROUP_ID_CONFIG, deConfiguration.getDistributionStatusTopic().getConsumerGroup());
62         properties.put(CommonClientConfigs.BOOTSTRAP_SERVERS_CONFIG, deConfiguration.getKafkaBootStrapServers());
63         properties.put(CommonClientConfigs.SECURITY_PROTOCOL_CONFIG, "SASL_PLAINTEXT");
64         properties.put(ConsumerConfig.ALLOW_AUTO_CREATE_TOPICS_CONFIG, false);
65         properties.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "latest");
66         properties.put(SaslConfigs.SASL_MECHANISM, getKafkaSaslMechanism());
67
68         properties.put(SaslConfigs.SASL_JAAS_CONFIG, getKafkaSaslJaasConfig());
69         kafkaConsumer = new KafkaConsumer<>(properties);
70     }
71
72     /**
73      *
74      * @param kafkaConsumer a kafkaConsumer to use within the class
75      * @param deConfiguration - Configuration to pass into the class
76      */
77     @VisibleForTesting
78     SdcKafkaConsumer(KafkaConsumer kafkaConsumer, DistributionEngineConfiguration deConfiguration){
79         this.deConfiguration = deConfiguration;
80         this.kafkaConsumer = kafkaConsumer;
81     }
82
83     /**
84      *
85      * @return the Sasl Jass Config
86      */
87     private String getKafkaSaslJaasConfig() {
88         String saslJaasConfFromEnv = System.getenv("SASL_JAAS_CONFIG");
89         if(saslJaasConfFromEnv != null) {
90             return saslJaasConfFromEnv;
91         } else {
92             throw new KafkaException("sasl.jaas.config not set for Kafka Consumer");
93         }
94     }
95     
96     private static String getKafkaSaslMechanism() throws KafkaException {
97         String saslMechanism = System.getenv("SASL_MECHANISM");
98         if(saslMechanism != null) {
99             return saslMechanism;
100         } else {
101             return DEFAULT_SASL_MECHANISM;
102         }
103     }
104
105     /**
106      *
107      * @param topic Topic in which to subscribe
108      */
109     public void subscribe(String topic) throws KafkaException {
110         if (!kafkaConsumer.subscription().contains(topic)) {
111             kafkaConsumer.subscribe(Collections.singleton(topic));
112         }
113     }
114
115     /**
116      *
117      * @return The list of messages for a specified topic, returned from the poll
118      */
119     public List<String> poll(String topicName) throws KafkaException {
120         log.info("SdcKafkaConsumer - polling for messages from Topic: {}", topicName);
121         List<String> msgs = new ArrayList<>();
122         ConsumerRecords<String, String> consumerRecordsForSpecificTopic = kafkaConsumer.poll(Duration.ofSeconds(deConfiguration.getDistributionStatusTopic().getPollingIntervalSec()));
123         for(ConsumerRecord<String, String> rec : consumerRecordsForSpecificTopic){
124             msgs.add(rec.value());
125         }
126         return msgs;
127     }
128 }