93b9a714f576d71847ae18eca1b8803947336643
[nonrtric/plt/ranpm.git] / datafilecollector / src / main / java / org / oran / datafile / tasks / CollectAndReportFiles.java
1 /*-
2  * ============LICENSE_START======================================================================
3  * Copyright (C) 2018, 2020 NOKIA Intellectual Property, 2018-2023 Nordix Foundation. All rights reserved.
4  * ===============================================================================================
5  * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
6  * in compliance with the License. You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software distributed under the License
11  * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
12  * or implied. See the License for the specific language governing permissions and limitations under
13  * the License.
14  * ============LICENSE_END========================================================================
15  */
16
17 package org.oran.datafile.tasks;
18
19 import com.google.gson.Gson;
20 import com.google.gson.GsonBuilder;
21
22 import java.nio.file.Files;
23 import java.nio.file.Path;
24 import java.nio.file.Paths;
25 import java.time.Duration;
26 import java.util.ArrayList;
27 import java.util.HashMap;
28 import java.util.Map;
29
30 import org.apache.kafka.clients.producer.ProducerConfig;
31 import org.apache.kafka.clients.producer.ProducerRecord;
32 import org.apache.kafka.common.header.Header;
33 import org.apache.kafka.common.header.internals.RecordHeader;
34 import org.apache.kafka.common.serialization.StringSerializer;
35 import org.oran.datafile.configuration.AppConfig;
36 import org.oran.datafile.configuration.CertificateConfig;
37 import org.oran.datafile.datastore.DataStore;
38 import org.oran.datafile.datastore.DataStore.Bucket;
39 import org.oran.datafile.exceptions.DatafileTaskException;
40 import org.oran.datafile.http.HttpsClientConnectionManagerUtil;
41 import org.oran.datafile.model.Counters;
42 import org.oran.datafile.model.FileData;
43 import org.oran.datafile.model.FilePublishInformation;
44 import org.oran.datafile.model.FileReadyMessage;
45 import org.oran.datafile.oauth2.SecurityContext;
46 import org.slf4j.Logger;
47 import org.slf4j.LoggerFactory;
48 import org.springframework.stereotype.Component;
49
50 import reactor.core.publisher.Flux;
51 import reactor.core.publisher.Mono;
52 import reactor.core.scheduler.Scheduler;
53 import reactor.core.scheduler.Schedulers;
54 import reactor.kafka.sender.KafkaSender;
55 import reactor.kafka.sender.SenderOptions;
56 import reactor.kafka.sender.SenderRecord;
57 import reactor.kafka.sender.SenderResult;
58 import reactor.util.retry.Retry;
59
60 /**
61  * This implements the main flow of the data file collector. Fetch file ready
62  * events from the
63  * message router, fetch new files from the PNF publish these in the data
64  * router.
65  */
66 @Component
67 public class CollectAndReportFiles {
68
69     private static Gson gson = new GsonBuilder() //
70         .disableHtmlEscaping() //
71         .create(); //
72
73     private static final long FILE_TRANSFER_MAX_RETRIES = 2;
74     private static final Duration FILE_TRANSFER_INITIAL_RETRY_TIMEOUT = Duration.ofSeconds(2);
75
76     private static final Logger logger = LoggerFactory.getLogger(CollectAndReportFiles.class);
77
78     private final AppConfig appConfig;
79
80     private Counters counters = new Counters();
81
82     private final KafkaSender<String, String> kafkaSender;
83
84     private final DataStore dataStore;
85
86     private final SecurityContext securityContext;
87
88     /**
89      * Constructor for task registration in Datafile Workflow.
90      *
91      * @param applicationConfiguration - application configuration
92      */
93     public CollectAndReportFiles(SecurityContext securityContext, AppConfig applicationConfiguration) {
94         this.appConfig = applicationConfiguration;
95         this.kafkaSender = KafkaSender.create(kafkaSenderOptions());
96         this.securityContext = securityContext;
97         initCerts();
98
99         this.dataStore = DataStore.create(applicationConfiguration);
100
101         start();
102     }
103
104     private void initCerts() {
105         try {
106             CertificateConfig certificateConfig = appConfig.getCertificateConfiguration();
107             HttpsClientConnectionManagerUtil.setupOrUpdate(certificateConfig.keyCert, certificateConfig.keyPasswordPath,
108                 certificateConfig.trustedCa, certificateConfig.trustedCaPasswordPath, true);
109         } catch (DatafileTaskException e) {
110             logger.error("Could not setup HttpsClient certs, reason: {}", e.getMessage());
111         }
112     }
113
114     /**
115      * Main function for scheduling for the file collection Workflow.
116      */
117     public void start() {
118         start(0);
119     }
120
121     private void start(int delayMillis) {
122         try {
123             logger.trace("Starting");
124             if (appConfig.isS3Enabled()) {
125                 this.dataStore.create(Bucket.FILES).subscribe();
126                 this.dataStore.create(Bucket.LOCKS).subscribe();
127             }
128             Thread.sleep(delayMillis);
129             createMainTask().subscribe(null, s -> start(2000), null);
130         } catch (Exception e) {
131             logger.error("Unexpected exception: {}", e.toString(), e);
132             Thread.currentThread().interrupt();
133         }
134     }
135
136     Flux<FilePublishInformation> createMainTask() {
137         final int noOfWorkerThreads = appConfig.getNoOfWorkerThreads();
138         Scheduler scheduler = Schedulers.newParallel("FileCollectorWorker", noOfWorkerThreads);
139         return fetchFromKafka() //
140             .doOnNext(fileReadyMessage -> counters.threadPoolQueueSize.incrementAndGet()) //
141             .doOnNext(fileReadyMessage -> counters.incNoOfReceivedEvents()) //
142             .parallel(noOfWorkerThreads) // Each FileReadyMessage in a separate thread
143             .runOn(scheduler) //
144             .doOnNext(fileReadyMessage -> counters.threadPoolQueueSize.decrementAndGet()) //
145             .flatMap(fileReadyMessage -> Flux.fromIterable(FileData.createFileData(fileReadyMessage)), true, 1) //
146             .flatMap(this::filterNotFetched, false, 1, 1) //
147             .flatMap(this::fetchFile, false, 1, 1) //
148             .flatMap(data -> reportFetchedFile(data, appConfig.getCollectedFileTopic()), false, 1) //
149             .sequential() //
150             .doOnError(t -> logger.error("Received error: {}", t.toString())); //
151     }
152
153     private Mono<FileData> deleteLock(FileData info) {
154         return dataStore.deleteLock(lockName(info.name())).map(b -> info); //
155     }
156
157     private Mono<FilePublishInformation> moveFileToS3Bucket(FilePublishInformation info) {
158         if (this.appConfig.isS3Enabled()) {
159             return dataStore.copyFileTo(locaFilePath(info), info.getName())
160                 .doOnError(t -> logger.warn("Failed to store file '{}' in S3 {}", info.getName(), t.getMessage())) //
161                 .retryWhen(Retry.backoff(4, Duration.ofMillis(1000))) //
162                 .map(f -> info) //
163                 .doOnError(t -> logger.error("Failed to store file '{}' in S3 after retries {}", info.getName(),
164                     t.getMessage())) //
165                 .doOnNext(n -> logger.debug("Stored file in S3: {}", info.getName())) //
166                 .doOnNext(sig -> deleteLocalFile(info));
167         } else {
168             return Mono.just(info);
169         }
170     }
171
172     private Mono<FileData> filterNotFetched(FileData fileData) {
173         Path localPath = fileData.getLocalFilePath(this.appConfig);
174
175         return dataStore.fileExists(Bucket.FILES, fileData.name()) //
176             .filter(exists -> !exists) //
177             .filter(exists -> !localPath.toFile().exists()) //
178             .map(f -> fileData); //
179
180     }
181
182     private String lockName(String fileName) {
183         return fileName + ".lck";
184     }
185
186     private Path locaFilePath(FilePublishInformation info) {
187         return Paths.get(appConfig.getCollectedFilesPath(), info.getName());
188     }
189
190     private void deleteLocalFile(FilePublishInformation info) {
191         Path path = locaFilePath(info);
192         try {
193             Files.delete(path);
194         } catch (Exception e) {
195             logger.warn("Could not delete local file: {}, reason:{}", path, e.getMessage());
196         }
197     }
198
199     private Flux<FilePublishInformation> reportFetchedFile(FilePublishInformation fileData, String topic) {
200         String json = gson.toJson(fileData);
201         return sendDataToStream(topic, fileData.getSourceName(), json) //
202             .map(result -> fileData);
203     }
204
205     public Flux<SenderResult<Integer>> sendDataToStream(String topic, String sourceName, String value) {
206         return sendDataToKafkaStream(Flux.just(senderRecord(topic, sourceName, value)));
207     }
208
209     private SenderRecord<String, String, Integer> senderRecord(String topic, String sourceName, String value) {
210         int correlationMetadata = 2;
211         String key = null;
212         var producerRecord = new ProducerRecord<>(topic, null, null, key, value, kafkaHeaders(sourceName));
213         return SenderRecord.create(producerRecord, correlationMetadata);
214     }
215
216     private Iterable<Header> kafkaHeaders(String sourceName) {
217         ArrayList<Header> result = new ArrayList<>();
218         Header h = new RecordHeader("SourceName", sourceName.getBytes());
219         result.add(h);
220         return result;
221     }
222
223     private Flux<SenderResult<Integer>> sendDataToKafkaStream(Flux<SenderRecord<String, String, Integer>> dataToSend) {
224         return kafkaSender.send(dataToSend) //
225             .doOnError(e -> logger.error("Send to kafka failed", e));
226     }
227
228     private SenderOptions<String, String> kafkaSenderOptions() {
229         String bootstrapServers = this.appConfig.getKafkaBootStrapServers();
230
231         Map<String, Object> props = new HashMap<>();
232         props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServers);
233         props.put(ProducerConfig.ACKS_CONFIG, "all");
234         props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
235         props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
236         this.appConfig.addKafkaSecurityProps(props);
237         return SenderOptions.create(props);
238     }
239
240     public Counters getCounters() {
241         return this.counters;
242     }
243
244     protected FileCollector createFileCollector() {
245         return new FileCollector(securityContext, appConfig, counters);
246     }
247
248     private Mono<FilePublishInformation> fetchFile(FileData fileData) {
249         return this.dataStore.createLock(lockName(fileData.name())).filter(granted -> granted) //
250             .map(granted -> createFileCollector()) //
251             .flatMap(collector -> collector.collectFile(fileData, FILE_TRANSFER_MAX_RETRIES,
252                 FILE_TRANSFER_INITIAL_RETRY_TIMEOUT)) //
253             .flatMap(this::moveFileToS3Bucket) //
254             .doOnNext(b -> deleteLock(fileData).subscribe()) //
255             .doOnError(b -> deleteLock(fileData).subscribe()) //
256             .onErrorResume(exception -> handleFetchFileFailure(fileData, exception)); //
257     }
258
259     private Mono<FilePublishInformation> handleFetchFileFailure(FileData fileData, Throwable t) {
260         Path localFilePath = fileData.getLocalFilePath(this.appConfig);
261         logger.error("File fetching failed, path {}, reason: {}", fileData.remoteFilePath(), t.getMessage());
262         deleteFile(localFilePath);
263         if (FileData.Scheme.isFtpScheme(fileData.scheme())) {
264             counters.incNoOfFailedFtp();
265         } else {
266             counters.incNoOfFailedHttp();
267         }
268         return Mono.empty();
269     }
270
271     /**
272      * Fetch more messages from the message router. This is done in a
273      * polling/blocking fashion.
274      */
275     private Flux<FileReadyMessage> fetchFromKafka() {
276         KafkaTopicListener listener = new KafkaTopicListener(this.appConfig);
277         return listener.getFlux() //
278             .flatMap(this::parseReceivedFileReadyMessage, 1);
279
280     }
281
282     Mono<FileReadyMessage> parseReceivedFileReadyMessage(KafkaTopicListener.DataFromTopic data) {
283         try {
284             FileReadyMessage msg = gson.fromJson(data.value, FileReadyMessage.class);
285             logger.debug("Received: {}", msg);
286             return Mono.just(msg);
287         } catch (Exception e) {
288             logger.warn("Could not parse received: {}, reason: {}", data.value, e.getMessage());
289             return Mono.empty();
290         }
291     }
292
293     private static void deleteFile(Path localFile) {
294         logger.trace("Deleting file: {}", localFile);
295         try {
296             Files.delete(localFile);
297         } catch (Exception e) {
298             logger.trace("Could not delete file: {}, reason: {}", localFile, e.getMessage());
299         }
300     }
301 }