3dd2475595cc2885cec48865b392a0a0d8d28829
[nonrtric/plt/ranpm.git] / pmproducer / src / main / java / org / oran / pmproducer / tasks / TopicListener.java
1 /*-
2  * ========================LICENSE_START=================================
3  * O-RAN-SC
4  * %%
5  * Copyright (C) 2023 Nordix Foundation
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
21 package org.oran.pmproducer.tasks;
22
23 import java.io.ByteArrayInputStream;
24 import java.io.IOException;
25 import java.util.Collections;
26 import java.util.HashMap;
27 import java.util.Map;
28 import java.util.zip.GZIPInputStream;
29
30 import lombok.Getter;
31 import lombok.Setter;
32 import lombok.ToString;
33
34 import org.apache.kafka.clients.consumer.ConsumerConfig;
35 import org.apache.kafka.clients.consumer.ConsumerRecord;
36 import org.apache.kafka.common.header.Header;
37 import org.apache.kafka.common.serialization.ByteArrayDeserializer;
38 import org.oran.pmproducer.configuration.ApplicationConfig;
39 import org.oran.pmproducer.datastore.DataStore;
40 import org.oran.pmproducer.filter.PmReport;
41 import org.oran.pmproducer.repository.InfoType;
42 import org.slf4j.Logger;
43 import org.slf4j.LoggerFactory;
44
45 import reactor.core.publisher.Flux;
46 import reactor.core.publisher.Mono;
47 import reactor.kafka.receiver.KafkaReceiver;
48 import reactor.kafka.receiver.ReceiverOptions;
49
50 /**
51  * The class streams incoming requests from a Kafka topic and sends them further
52  * to a multi cast sink, which several other streams can connect to.
53  */
54 @SuppressWarnings("squid:S2629") // Invoke method(s) only conditionally
55 public class TopicListener {
56
57     @ToString
58     public static class DataFromTopic {
59         public final byte[] key;
60         public final byte[] value;
61
62         public final String infoTypeId;
63
64         public final Iterable<Header> headers;
65
66         private static byte[] noBytes = new byte[0];
67
68         @Getter
69         @Setter
70         @ToString.Exclude
71         private PmReport cachedPmReport;
72
73         public DataFromTopic(String typeId, Iterable<Header> headers, byte[] key, byte[] value) {
74             this.key = key == null ? noBytes : key;
75             this.value = value == null ? noBytes : value;
76             this.infoTypeId = typeId;
77             this.headers = headers;
78         }
79
80         public String valueAsString() {
81             return new String(this.value);
82         }
83
84         public static final String ZIPPED_PROPERTY = "gzip";
85         public static final String TYPE_ID_PROPERTY = "type-id";
86
87         public boolean isZipped() {
88             if (headers == null) {
89                 return false;
90             }
91             for (Header h : headers) {
92                 if (h.key().equals(ZIPPED_PROPERTY)) {
93                     return true;
94                 }
95             }
96             return false;
97         }
98
99         public String getTypeIdFromHeaders() {
100             if (headers == null) {
101                 return "";
102             }
103             for (Header h : headers) {
104                 if (h.key().equals(TYPE_ID_PROPERTY)) {
105                     return new String(h.value());
106                 }
107             }
108             return "";
109         }
110     }
111
112     private static final Logger logger = LoggerFactory.getLogger(TopicListener.class);
113     private final ApplicationConfig applicationConfig;
114     private final InfoType type;
115     private Flux<DataFromTopic> dataFromTopic;
116     private static com.google.gson.Gson gson = new com.google.gson.GsonBuilder().disableHtmlEscaping().create();
117     private final DataStore dataStore;
118
119     @Setter
120     private String kafkaGroupId;
121
122     public TopicListener(ApplicationConfig applConfig, InfoType type) {
123         this.applicationConfig = applConfig;
124         this.type = type;
125         this.dataStore = DataStore.create(applConfig);
126         this.kafkaGroupId = this.type.getKafkaGroupId();
127     }
128
129     public Flux<DataFromTopic> getFlux() {
130         if (this.dataFromTopic == null) {
131             this.dataFromTopic = start(this.type.getKafkaClientId(this.applicationConfig));
132         }
133         return this.dataFromTopic;
134     }
135
136     private Flux<DataFromTopic> start(String clientId) {
137         logger.debug("Listening to kafka topic: {} type :{}", this.type.getKafkaInputTopic(), type.getId());
138
139         return receiveFromKafka(clientId) //
140                 .filter(t -> t.value().length > 0 || t.key().length > 0) //
141                 .map(input -> new DataFromTopic(this.type.getId(), input.headers(), input.key(), input.value())) //
142                 .flatMap(data -> getDataFromFileIfNewPmFileEvent(data, type, dataStore)) //
143                 .publish() //
144                 .autoConnect(1);
145     }
146
147     public Flux<ConsumerRecord<byte[], byte[]>> receiveFromKafka(String clientId) {
148         return KafkaReceiver.create(kafkaInputProperties(clientId)) //
149                 .receiveAutoAck() //
150                 .concatMap(consumerRecord -> consumerRecord) //
151                 .doOnNext(input -> logger.trace("Received from kafka topic: {}", this.type.getKafkaInputTopic())) //
152                 .doOnError(t -> logger.error("Received error: {}", t.getMessage())) //
153                 .onErrorResume(t -> Mono.empty()) //
154                 .doFinally(sig -> logger.error("TopicListener stopped, type: {}, reason: {}", this.type.getId(), sig));
155     }
156
157     private ReceiverOptions<byte[], byte[]> kafkaInputProperties(String clientId) {
158         Map<String, Object> props = new HashMap<>();
159         if (this.applicationConfig.getKafkaBootStrapServers().isEmpty()) {
160             logger.error("No kafka boostrap server is setup");
161         }
162
163         props.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, "false");
164         props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, this.applicationConfig.getKafkaBootStrapServers());
165         props.put(ConsumerConfig.GROUP_ID_CONFIG, kafkaGroupId);
166         props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, ByteArrayDeserializer.class);
167         props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, ByteArrayDeserializer.class);
168         props.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, false);
169         props.put(ConsumerConfig.CLIENT_ID_CONFIG, clientId + "_" + kafkaGroupId);
170
171         this.applicationConfig.addKafkaSecurityProps(props);
172
173         return ReceiverOptions.<byte[], byte[]>create(props)
174                 .subscription(Collections.singleton(this.type.getKafkaInputTopic()));
175     }
176
177     public static Mono<DataFromTopic> getDataFromFileIfNewPmFileEvent(DataFromTopic data, InfoType type,
178             DataStore fileStore) {
179         try {
180             if (data.value.length > 200) {
181                 return Mono.just(data);
182             }
183
184             NewFileEvent ev = gson.fromJson(data.valueAsString(), NewFileEvent.class);
185
186             if (ev.getFilename() == null) {
187                 logger.warn("Ignoring received message: {}", data);
188                 return Mono.empty();
189             }
190             logger.trace("Reading PM measurements, type: {}, inputTopic: {}", type.getId(), type.getKafkaInputTopic());
191             return fileStore.readObject(DataStore.Bucket.FILES, ev.getFilename()) //
192                     .map(bytes -> unzip(bytes, ev.getFilename())) //
193                     .map(bytes -> new DataFromTopic(data.infoTypeId, data.headers, data.key, bytes));
194
195         } catch (Exception e) {
196             return Mono.just(data);
197         }
198     }
199
200     public static byte[] unzip(byte[] bytes) throws IOException {
201         try (final GZIPInputStream gzipInput = new GZIPInputStream(new ByteArrayInputStream(bytes))) {
202             return gzipInput.readAllBytes();
203         }
204     }
205
206     private static byte[] unzip(byte[] bytes, String fileName) {
207         try {
208             return fileName.endsWith(".gz") ? unzip(bytes) : bytes;
209         } catch (IOException e) {
210             logger.error("Error while decompression, file: {}, reason: {}", fileName, e.getMessage());
211             return new byte[0];
212         }
213
214     }
215
216 }