bc67e6631c9f027f8be0a57f8ca9394d9ce68af4
[ccsdk/oran.git] /
1 /*-
2  * ========================LICENSE_START=================================
3  * ONAP : ccsdk oran
4  * ======================================================================
5  * Copyright (C) 2020 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
21 package org.onap.ccsdk.oran.a1policymanagementservice.dmaap;
22
23 import com.google.gson.Gson;
24 import com.google.gson.GsonBuilder;
25 import com.google.gson.JsonArray;
26 import com.google.gson.JsonElement;
27 import com.google.gson.JsonParser;
28
29 import java.time.Duration;
30 import java.util.ArrayList;
31 import java.util.List;
32
33 import org.onap.ccsdk.oran.a1policymanagementservice.clients.AsyncRestClient;
34 import org.onap.ccsdk.oran.a1policymanagementservice.clients.AsyncRestClientFactory;
35 import org.onap.ccsdk.oran.a1policymanagementservice.configuration.ApplicationConfig;
36 import org.slf4j.Logger;
37 import org.slf4j.LoggerFactory;
38 import org.springframework.beans.factory.annotation.Autowired;
39 import org.springframework.beans.factory.annotation.Value;
40 import org.springframework.http.HttpStatus;
41 import org.springframework.stereotype.Component;
42
43 import reactor.core.publisher.Flux;
44 import reactor.core.publisher.FluxSink;
45 import reactor.core.publisher.Mono;
46
47 /**
48  * The class fetches incoming requests from DMAAP. It uses the timeout parameter
49  * that lets the MessageRouter keep the connection with the Kafka open until
50  * requests are sent in.
51  *
52  * <p>
53  * this service will regularly check the configuration and start polling DMaaP
54  * if the configuration is added. If the DMaaP configuration is removed, then
55  * the service will stop polling and resume checking for configuration.
56  *
57  * <p>
58  * Each received request is processed by {@link DmaapMessageHandler}.
59  */
60 @Component
61 public class DmaapMessageConsumer {
62
63     protected static final Duration TIME_BETWEEN_DMAAP_RETRIES = Duration.ofSeconds(10);
64
65     private static final Logger logger = LoggerFactory.getLogger(DmaapMessageConsumer.class);
66
67     private final ApplicationConfig applicationConfig;
68
69     private DmaapMessageHandler dmaapMessageHandler = null;
70
71     private final Gson gson;
72
73     private final AsyncRestClientFactory restClientFactory;
74
75     private final InfiniteFlux infiniteSubmitter = new InfiniteFlux();
76
77     @Value("${server.http-port}")
78     private int localServerHttpPort;
79
80     private static class InfiniteFlux {
81         private FluxSink<Integer> sink;
82         private int counter = 0;
83
84         public synchronized Flux<Integer> start() {
85             stop();
86             return Flux.create(this::next).doOnRequest(this::onRequest);
87         }
88
89         public synchronized void stop() {
90             if (this.sink != null) {
91                 this.sink.complete();
92                 this.sink = null;
93             }
94         }
95
96         void onRequest(long no) {
97             logger.debug("InfiniteFlux.onRequest {}", no);
98             for (long i = 0; i < no; ++i) {
99                 sink.next(counter++);
100             }
101         }
102
103         void next(FluxSink<Integer> sink) {
104             logger.debug("InfiniteFlux.next");
105             this.sink = sink;
106             sink.next(counter++);
107         }
108
109     }
110
111     @Autowired
112     public DmaapMessageConsumer(ApplicationConfig applicationConfig) {
113         this.applicationConfig = applicationConfig;
114         GsonBuilder gsonBuilder = new GsonBuilder();
115         this.gson = gsonBuilder.create();
116         this.restClientFactory = new AsyncRestClientFactory(applicationConfig.getWebClientConfig());
117     }
118
119     /**
120      * Starts the DMAAP consumer. If there is a DMaaP configuration, it will start
121      * polling for messages. Otherwise it will check regularly for the
122      * configuration.
123      *
124      */
125     public void start() {
126         infiniteSubmitter.stop();
127
128         createTask().subscribe(//
129                 value -> logger.debug("DmaapMessageConsumer next: {}", value), //
130                 throwable -> logger.error("DmaapMessageConsumer error: {}", throwable.getMessage()), //
131                 () -> logger.warn("DmaapMessageConsumer stopped") //
132         );
133     }
134
135     protected Flux<String> createTask() {
136         return infiniteFlux() //
137                 .flatMap(notUsed -> fetchFromDmaap(), 1) //
138                 .doOnNext(message -> logger.debug("Message Reveived from DMAAP : {}", message)) //
139                 .flatMap(this::parseReceivedMessage, 1)//
140                 .flatMap(this::handleDmaapMsg, 1) //
141                 .onErrorResume(throwable -> Mono.empty());
142     }
143
144     protected Flux<Integer> infiniteFlux() {
145         return infiniteSubmitter.start();
146     }
147
148     protected Mono<Object> delay() {
149         return Mono.delay(TIME_BETWEEN_DMAAP_RETRIES).flatMap(o -> Mono.empty());
150     }
151
152     private <T> List<T> parseList(String jsonString, Class<T> clazz) {
153         List<T> result = new ArrayList<>();
154         JsonArray jsonArr = JsonParser.parseString(jsonString).getAsJsonArray();
155         for (JsonElement jsonElement : jsonArr) {
156             // The element can either be a JsonObject or a JsonString
157             if (jsonElement.isJsonPrimitive()) {
158                 T json = gson.fromJson(jsonElement.getAsString(), clazz);
159                 result.add(json);
160             } else {
161                 T json = gson.fromJson(jsonElement.toString(), clazz);
162                 result.add(json);
163             }
164         }
165         return result;
166     }
167
168     protected boolean isDmaapConfigured() {
169         String producerTopicUrl = applicationConfig.getDmaapProducerTopicUrl();
170         String consumerTopicUrl = applicationConfig.getDmaapConsumerTopicUrl();
171         return (producerTopicUrl != null && consumerTopicUrl != null && !producerTopicUrl.isEmpty()
172                 && !consumerTopicUrl.isEmpty());
173     }
174
175     protected Mono<String> handleDmaapMsg(DmaapRequestMessage dmaapRequestMessage) {
176         return getDmaapMessageHandler().handleDmaapMsg(dmaapRequestMessage);
177     }
178
179     protected Mono<String> getFromMessageRouter(String topicUrl) {
180         logger.trace("getFromMessageRouter {}", topicUrl);
181         AsyncRestClient c = restClientFactory.createRestClientNoHttpProxy("");
182         return c.get(topicUrl);
183     }
184
185     protected Flux<DmaapRequestMessage> parseReceivedMessage(String jsonString) {
186         try {
187             logger.trace("parseMessages {}", jsonString);
188             return Flux.fromIterable(parseList(jsonString, DmaapRequestMessage.class));
189         } catch (Exception e) {
190             logger.error("parseMessages error {}", jsonString);
191             return sendErrorResponse("Could not parse: " + jsonString) //
192                     .flatMapMany(s -> Flux.empty());
193         }
194     }
195
196     protected Mono<String> sendErrorResponse(String response) {
197         logger.debug("sendErrorResponse {}", response);
198         DmaapRequestMessage fakeRequest = DmaapRequestMessage.builder() //
199                 .apiVersion("") //
200                 .correlationId("") //
201                 .operation(DmaapRequestMessage.Operation.PUT) //
202                 .originatorId("") //
203                 .payload(null) //
204                 .requestId("") //
205                 .target("") //
206                 .timestamp("") //
207                 .url("URL") //
208                 .build();
209         return getDmaapMessageHandler().sendDmaapResponse(response, fakeRequest, HttpStatus.BAD_REQUEST) //
210                 .onErrorResume(e -> Mono.empty());
211     }
212
213     private Mono<String> fetchFromDmaap() {
214         if (!this.isDmaapConfigured()) {
215             logger.debug("fetchFromDmaap, no action DMAAP not configured");
216             return delay().flatMap(o -> Mono.empty());
217         }
218         logger.debug("fetchFromDmaap");
219         String topicUrl = this.applicationConfig.getDmaapConsumerTopicUrl();
220
221         return getFromMessageRouter(topicUrl) //
222                 .onErrorResume(throwable -> delay().flatMap(o -> Mono.empty()));
223     }
224
225     private DmaapMessageHandler getDmaapMessageHandler() {
226         if (this.dmaapMessageHandler == null) {
227             String pmsBaseUrl = "http://localhost:" + this.localServerHttpPort;
228             AsyncRestClient pmsClient = restClientFactory.createRestClientNoHttpProxy(pmsBaseUrl);
229             AsyncRestClient producer =
230                     restClientFactory.createRestClientNoHttpProxy(this.applicationConfig.getDmaapProducerTopicUrl());
231             this.dmaapMessageHandler = new DmaapMessageHandler(producer, pmsClient);
232         }
233         return this.dmaapMessageHandler;
234     }
235
236 }