f677502c664ad41834eeca2f174f4e8a500db0df
[nonrtric.git] / dmaap-adaptor-java / src / main / java / org / oran / dmaapadapter / tasks / KafkaJobDataConsumer.java
1 /*-
2  * ========================LICENSE_START=================================
3  * O-RAN-SC
4  * %%
5  * Copyright (C) 2021 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.dmaapadapter.tasks;
22
23 import lombok.Getter;
24
25 import org.oran.dmaapadapter.repository.Job;
26 import org.slf4j.Logger;
27 import org.slf4j.LoggerFactory;
28 import org.springframework.http.MediaType;
29 import org.springframework.web.reactive.function.client.WebClientResponseException;
30
31 import reactor.core.Disposable;
32 import reactor.core.publisher.Flux;
33 import reactor.core.publisher.Mono;
34 import reactor.core.publisher.Sinks.Many;
35
36 /**
37  * The class streams data from a multi cast sink and sends the data to the Job
38  * owner via REST calls.
39  */
40 @SuppressWarnings("squid:S2629") // Invoke method(s) only conditionally
41 public class KafkaJobDataConsumer {
42     private static final Logger logger = LoggerFactory.getLogger(KafkaJobDataConsumer.class);
43     @Getter
44     private final Job job;
45     private Disposable subscription;
46     private final ErrorStats errorStats = new ErrorStats();
47
48     private class ErrorStats {
49         private int consumerFaultCounter = 0;
50         private boolean kafkaError = false; // eg. overflow
51
52         public void handleOkFromConsumer() {
53             this.consumerFaultCounter = 0;
54         }
55
56         public void handleException(Throwable t) {
57             if (t instanceof WebClientResponseException) {
58                 ++this.consumerFaultCounter;
59             } else {
60                 kafkaError = true;
61             }
62         }
63
64         public boolean isItHopeless() {
65             final int STOP_AFTER_ERRORS = 5;
66             return kafkaError || consumerFaultCounter > STOP_AFTER_ERRORS;
67         }
68
69         public void resetKafkaErrors() {
70             kafkaError = false;
71         }
72     }
73
74     public KafkaJobDataConsumer(Job job) {
75         this.job = job;
76     }
77
78     public synchronized void start(Many<String> input) {
79         stop();
80         this.errorStats.resetKafkaErrors();
81         this.subscription = getMessagesFromKafka(input, job) //
82                 .flatMap(this::postToClient, job.getParameters().getMaxConcurrency()) //
83                 .onErrorResume(this::handleError) //
84                 .subscribe(this::handleConsumerSentOk, //
85                         this::handleExceptionInStream, //
86                         () -> logger.warn("KafkaMessageConsumer stopped jobId: {}", job.getId()));
87     }
88
89     private void handleExceptionInStream(Throwable t) {
90         logger.warn("KafkaMessageConsumer exception: {}, jobId: {}", t.getMessage(), job.getId());
91         stop();
92     }
93
94     private Mono<String> postToClient(String body) {
95         logger.debug("Sending to consumer {} {} {}", job.getId(), job.getCallbackUrl(), body);
96         MediaType contentType = this.job.isBuffered() ? MediaType.APPLICATION_JSON : null;
97         return job.getConsumerRestClient().post("", body, contentType);
98     }
99
100     public synchronized void stop() {
101         if (this.subscription != null) {
102             subscription.dispose();
103             subscription = null;
104         }
105     }
106
107     public synchronized boolean isRunning() {
108         return this.subscription != null;
109     }
110
111     private Flux<String> getMessagesFromKafka(Many<String> input, Job job) {
112         Flux<String> result = input.asFlux() //
113                 .filter(job::isFilterMatch);
114
115         if (job.isBuffered()) {
116             result = result.map(this::quote) //
117                     .bufferTimeout( //
118                             job.getParameters().getBufferTimeout().getMaxSize(), //
119                             job.getParameters().getBufferTimeout().getMaxTime()) //
120                     .map(Object::toString);
121         }
122         return result;
123     }
124
125     private String quote(String str) {
126         final String q = "\"";
127         return q + str.replace(q, "\\\"") + q;
128     }
129
130     private Mono<String> handleError(Throwable t) {
131         logger.warn("exception: {} job: {}", t.getMessage(), job.getId());
132         this.errorStats.handleException(t);
133         if (this.errorStats.isItHopeless()) {
134             return Mono.error(t);
135         } else {
136             return Mono.empty(); // Ignore
137         }
138     }
139
140     private void handleConsumerSentOk(String data) {
141         this.errorStats.handleOkFromConsumer();
142     }
143
144 }