94888c3877e4165646d66ce1dde631c67c503f24
[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.lang.invoke.MethodHandles;
30 import java.time.Duration;
31 import java.util.ArrayList;
32 import java.util.List;
33
34 import org.onap.ccsdk.oran.a1policymanagementservice.clients.AsyncRestClient;
35 import org.onap.ccsdk.oran.a1policymanagementservice.clients.AsyncRestClientFactory;
36 import org.onap.ccsdk.oran.a1policymanagementservice.clients.SecurityContext;
37 import org.onap.ccsdk.oran.a1policymanagementservice.configuration.ApplicationConfig;
38 import org.slf4j.Logger;
39 import org.slf4j.LoggerFactory;
40 import org.springframework.beans.factory.annotation.Autowired;
41 import org.springframework.beans.factory.annotation.Value;
42 import org.springframework.http.HttpStatus;
43 import org.springframework.stereotype.Component;
44
45 import reactor.core.publisher.Flux;
46 import reactor.core.publisher.FluxSink;
47 import reactor.core.publisher.Mono;
48
49 /**
50  * The class fetches incoming requests from DMAAP. It uses the timeout parameter
51  * that lets the MessageRouter keep the connection with the Kafka open until
52  * requests are sent in.
53  *
54  * <p>
55  * this service will regularly check the configuration and start polling DMaaP
56  * if the configuration is added. If the DMaaP configuration is removed, then
57  * the service will stop polling and resume checking for configuration.
58  *
59  * <p>
60  * Each received request is processed by {@link DmaapMessageHandler}.
61  */
62 @Component
63 public class DmaapMessageConsumer {
64
65     protected static final Duration TIME_BETWEEN_DMAAP_RETRIES = Duration.ofSeconds(10);
66
67     private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
68
69     private final ApplicationConfig applicationConfig;
70
71     private DmaapMessageHandler dmaapMessageHandler = null;
72
73     private final Gson gson;
74
75     private final AsyncRestClientFactory restClientFactory;
76
77     private final InfiniteFlux infiniteSubmitter = new InfiniteFlux();
78
79     @Value("${server.http-port}")
80     private int localServerHttpPort;
81
82     private static class InfiniteFlux {
83         private FluxSink<Integer> sink;
84         private int counter = 0;
85
86         public synchronized Flux<Integer> start() {
87             stop();
88             return Flux.create(this::next).doOnRequest(this::onRequest);
89         }
90
91         public synchronized void stop() {
92             if (this.sink != null) {
93                 this.sink.complete();
94                 this.sink = null;
95             }
96         }
97
98         void onRequest(long no) {
99             for (long i = 0; i < no; ++i) {
100                 sink.next(counter++);
101             }
102         }
103
104         void next(FluxSink<Integer> sink) {
105             this.sink = sink;
106             sink.next(counter++);
107         }
108
109     }
110
111     @Autowired
112     public DmaapMessageConsumer(ApplicationConfig applicationConfig, SecurityContext securityContext) {
113         this.applicationConfig = applicationConfig;
114         GsonBuilder gsonBuilder = new GsonBuilder();
115         this.gson = gsonBuilder.create();
116         this.restClientFactory = new AsyncRestClientFactory(applicationConfig.getWebClientConfig(), securityContext);
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             return delay().flatMap(o -> Mono.empty());
216         }
217         logger.debug("fetchFromDmaap");
218         String topicUrl = this.applicationConfig.getDmaapConsumerTopicUrl();
219
220         return getFromMessageRouter(topicUrl) //
221                 .onErrorResume(throwable -> delay().flatMap(o -> Mono.empty()));
222     }
223
224     private DmaapMessageHandler getDmaapMessageHandler() {
225         if (this.dmaapMessageHandler == null) {
226             String pmsBaseUrl = "http://localhost:" + this.localServerHttpPort;
227             AsyncRestClient pmsClient = restClientFactory.createRestClientNoHttpProxy(pmsBaseUrl);
228             AsyncRestClient producer =
229                     restClientFactory.createRestClientNoHttpProxy(this.applicationConfig.getDmaapProducerTopicUrl());
230             this.dmaapMessageHandler = new DmaapMessageHandler(producer, pmsClient);
231         }
232         return this.dmaapMessageHandler;
233     }
234
235 }