bafa8453c9b51b35a78911ba05732495c34babc5
[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.common.collect.Iterables;
24 import com.google.gson.Gson;
25 import com.google.gson.GsonBuilder;
26 import com.google.gson.JsonArray;
27 import com.google.gson.JsonElement;
28 import com.google.gson.JsonParser;
29 import com.google.gson.TypeAdapterFactory;
30
31 import java.time.Duration;
32 import java.util.ArrayList;
33 import java.util.List;
34 import java.util.Optional;
35 import java.util.ServiceLoader;
36
37 import org.onap.ccsdk.oran.a1policymanagementservice.clients.AsyncRestClient;
38 import org.onap.ccsdk.oran.a1policymanagementservice.configuration.ApplicationConfig;
39 import org.onap.ccsdk.oran.a1policymanagementservice.exceptions.ServiceException;
40 import org.slf4j.Logger;
41 import org.slf4j.LoggerFactory;
42 import org.springframework.beans.factory.annotation.Autowired;
43 import org.springframework.beans.factory.annotation.Value;
44 import org.springframework.http.HttpStatus;
45 import org.springframework.http.ResponseEntity;
46 import org.springframework.stereotype.Component;
47
48 /**
49  * The class fetches incoming requests from DMAAP. It uses the timeout parameter
50  * that lets the MessageRouter keep the connection with the Kafka open until
51  * requests are sent in.
52  *
53  * <p>
54  * this service will regularly check the configuration and start polling DMaaP
55  * if the configuration is added. If the DMaaP configuration is removed, then
56  * the service will stop polling and resume checking for configuration.
57  *
58  * <p>
59  * Each received request is processed by {@link DmaapMessageHandler}.
60  */
61 @Component
62 public class DmaapMessageConsumer {
63
64     protected static final Duration TIME_BETWEEN_DMAAP_RETRIES = Duration.ofSeconds(10);
65
66     private static final Logger logger = LoggerFactory.getLogger(DmaapMessageConsumer.class);
67
68     private final ApplicationConfig applicationConfig;
69
70     private DmaapMessageHandler dmaapMessageHandler = null;
71
72     private final Gson gson;
73
74     @Value("${server.http-port}")
75     private int localServerHttpPort;
76
77     @Autowired
78     public DmaapMessageConsumer(ApplicationConfig applicationConfig) {
79         this.applicationConfig = applicationConfig;
80         GsonBuilder gsonBuilder = new GsonBuilder();
81         ServiceLoader.load(TypeAdapterFactory.class).forEach(gsonBuilder::registerTypeAdapterFactory);
82         gson = gsonBuilder.create();
83     }
84
85     /**
86      * Starts the consumer. If there is a DMaaP configuration, it will start polling
87      * for messages. Otherwise it will check regularly for the configuration.
88      *
89      * @return the running thread, for test purposes.
90      */
91     public Thread start() {
92         Thread thread = new Thread(this::messageHandlingLoop);
93         thread.start();
94         return thread;
95     }
96
97     private void messageHandlingLoop() {
98         while (!isStopped()) {
99             try {
100                 if (isDmaapConfigured()) {
101                     Iterable<DmaapRequestMessage> dmaapMsgs = fetchAllMessages();
102                     if (dmaapMsgs != null && Iterables.size(dmaapMsgs) > 0) {
103                         logger.debug("Fetched all the messages from DMAAP and will start to process the messages");
104                         for (DmaapRequestMessage msg : dmaapMsgs) {
105                             processMsg(msg);
106                         }
107                     }
108                 } else {
109                     sleep(TIME_BETWEEN_DMAAP_RETRIES); // wait for configuration
110                 }
111             } catch (Exception e) {
112                 logger.warn("{}", e.getMessage());
113                 sleep(TIME_BETWEEN_DMAAP_RETRIES);
114             }
115         }
116     }
117
118     protected boolean isStopped() {
119         return false;
120     }
121
122     protected boolean isDmaapConfigured() {
123         String producerTopicUrl = applicationConfig.getDmaapProducerTopicUrl();
124         String consumerTopicUrl = applicationConfig.getDmaapConsumerTopicUrl();
125         return (producerTopicUrl != null && consumerTopicUrl != null && !producerTopicUrl.isEmpty()
126                 && !consumerTopicUrl.isEmpty());
127     }
128
129     private <T> List<T> parseList(String jsonString, Class<T> clazz) {
130         List<T> result = new ArrayList<>();
131         JsonArray jsonArr = JsonParser.parseString(jsonString).getAsJsonArray();
132         for (JsonElement jsonElement : jsonArr) {
133             // The element can either be a JsonObject or a JsonString
134             if (jsonElement.isJsonPrimitive()) {
135                 T json = gson.fromJson(jsonElement.getAsString(), clazz);
136                 result.add(json);
137             } else {
138                 T json = gson.fromJson(jsonElement.toString(), clazz);
139                 result.add(json);
140             }
141         }
142         return result;
143     }
144
145     private void sendErrorResponse(String response) {
146         DmaapRequestMessage fakeRequest = ImmutableDmaapRequestMessage.builder() //
147                 .apiVersion("") //
148                 .correlationId("") //
149                 .operation(DmaapRequestMessage.Operation.PUT) //
150                 .originatorId("") //
151                 .payload(Optional.empty()) //
152                 .requestId("") //
153                 .target("") //
154                 .timestamp("") //
155                 .url("URL") //
156                 .build();
157         getDmaapMessageHandler().sendDmaapResponse(response, fakeRequest, HttpStatus.BAD_REQUEST).block();
158     }
159
160     List<DmaapRequestMessage> parseMessages(String jsonString) throws ServiceException {
161         try {
162             return parseList(jsonString, DmaapRequestMessage.class);
163         } catch (Exception e) {
164             sendErrorResponse("Not parsable request received, reason:" + e.toString() + ", input :" + jsonString);
165             throw new ServiceException("Could not parse incomming request. Reason :" + e.getMessage());
166         }
167     }
168
169     protected Iterable<DmaapRequestMessage> fetchAllMessages() throws ServiceException {
170         String topicUrl = this.applicationConfig.getDmaapConsumerTopicUrl();
171         AsyncRestClient consumer = getMessageRouterConsumer();
172         ResponseEntity<String> response = consumer.getForEntity(topicUrl).block();
173         logger.debug("DMaaP consumer received {} : {}", response.getStatusCode(), response.getBody());
174         if (response.getStatusCode().is2xxSuccessful()) {
175             return parseMessages(response.getBody());
176         } else {
177             throw new ServiceException("Cannot fetch because of Error respons: " + response.getStatusCode().toString()
178                     + " " + response.getBody());
179         }
180     }
181
182     private void processMsg(DmaapRequestMessage msg) {
183         logger.debug("Message Reveived from DMAAP : {}", msg);
184         getDmaapMessageHandler().handleDmaapMsg(msg);
185     }
186
187     protected DmaapMessageHandler getDmaapMessageHandler() {
188         if (this.dmaapMessageHandler == null) {
189             String pmsBaseUrl = "http://localhost:" + this.localServerHttpPort;
190             AsyncRestClient pmsClient = new AsyncRestClient(pmsBaseUrl, this.applicationConfig.getWebClientConfig());
191             AsyncRestClient producer = new AsyncRestClient(this.applicationConfig.getDmaapProducerTopicUrl(),
192                     this.applicationConfig.getWebClientConfig());
193             this.dmaapMessageHandler = new DmaapMessageHandler(producer, pmsClient);
194         }
195         return this.dmaapMessageHandler;
196     }
197
198     protected void sleep(Duration duration) {
199         try {
200             Thread.sleep(duration.toMillis());
201         } catch (Exception e) {
202             logger.error("Failed to put the thread to sleep", e);
203         }
204     }
205
206     protected AsyncRestClient getMessageRouterConsumer() {
207         return new AsyncRestClient("", this.applicationConfig.getWebClientConfig());
208     }
209
210 }