3a365178394ab6e960941e0d858339c2ff0a6ae6
[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.clients.AsyncRestClientFactory;
39 import org.onap.ccsdk.oran.a1policymanagementservice.configuration.ApplicationConfig;
40 import org.onap.ccsdk.oran.a1policymanagementservice.exceptions.ServiceException;
41 import org.slf4j.Logger;
42 import org.slf4j.LoggerFactory;
43 import org.springframework.beans.factory.annotation.Autowired;
44 import org.springframework.beans.factory.annotation.Value;
45 import org.springframework.http.HttpStatus;
46 import org.springframework.http.ResponseEntity;
47 import org.springframework.stereotype.Component;
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(DmaapMessageConsumer.class);
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     @Value("${server.http-port}")
78     private int localServerHttpPort;
79
80     @Autowired
81     public DmaapMessageConsumer(ApplicationConfig applicationConfig) {
82         this.applicationConfig = applicationConfig;
83         GsonBuilder gsonBuilder = new GsonBuilder();
84         ServiceLoader.load(TypeAdapterFactory.class).forEach(gsonBuilder::registerTypeAdapterFactory);
85         gson = gsonBuilder.create();
86         this.restClientFactory = new AsyncRestClientFactory(applicationConfig.getWebClientConfig());
87     }
88
89     /**
90      * Starts the consumer. If there is a DMaaP configuration, it will start polling
91      * for messages. Otherwise it will check regularly for the configuration.
92      *
93      * @return the running thread, for test purposes.
94      */
95     public Thread start() {
96         Thread thread = new Thread(this::messageHandlingLoop);
97         thread.start();
98         return thread;
99     }
100
101     private void messageHandlingLoop() {
102         while (!isStopped()) {
103             try {
104                 if (isDmaapConfigured()) {
105                     Iterable<DmaapRequestMessage> dmaapMsgs = fetchAllMessages();
106                     if (dmaapMsgs != null && Iterables.size(dmaapMsgs) > 0) {
107                         logger.debug("Fetched all the messages from DMAAP and will start to process the messages");
108                         for (DmaapRequestMessage msg : dmaapMsgs) {
109                             processMsg(msg);
110                         }
111                     }
112                 } else {
113                     sleep(TIME_BETWEEN_DMAAP_RETRIES); // wait for configuration
114                 }
115             } catch (Exception e) {
116                 logger.warn("{}", e.getMessage());
117                 sleep(TIME_BETWEEN_DMAAP_RETRIES);
118             }
119         }
120     }
121
122     protected boolean isStopped() {
123         return false;
124     }
125
126     protected boolean isDmaapConfigured() {
127         String producerTopicUrl = applicationConfig.getDmaapProducerTopicUrl();
128         String consumerTopicUrl = applicationConfig.getDmaapConsumerTopicUrl();
129         return (producerTopicUrl != null && consumerTopicUrl != null && !producerTopicUrl.isEmpty()
130                 && !consumerTopicUrl.isEmpty());
131     }
132
133     private <T> List<T> parseList(String jsonString, Class<T> clazz) {
134         List<T> result = new ArrayList<>();
135         JsonArray jsonArr = JsonParser.parseString(jsonString).getAsJsonArray();
136         for (JsonElement jsonElement : jsonArr) {
137             // The element can either be a JsonObject or a JsonString
138             if (jsonElement.isJsonPrimitive()) {
139                 T json = gson.fromJson(jsonElement.getAsString(), clazz);
140                 result.add(json);
141             } else {
142                 T json = gson.fromJson(jsonElement.toString(), clazz);
143                 result.add(json);
144             }
145         }
146         return result;
147     }
148
149     private void sendErrorResponse(String response) {
150         DmaapRequestMessage fakeRequest = ImmutableDmaapRequestMessage.builder() //
151                 .apiVersion("") //
152                 .correlationId("") //
153                 .operation(DmaapRequestMessage.Operation.PUT) //
154                 .originatorId("") //
155                 .payload(Optional.empty()) //
156                 .requestId("") //
157                 .target("") //
158                 .timestamp("") //
159                 .url("URL") //
160                 .build();
161         getDmaapMessageHandler().sendDmaapResponse(response, fakeRequest, HttpStatus.BAD_REQUEST).block();
162     }
163
164     List<DmaapRequestMessage> parseMessages(String jsonString) throws ServiceException {
165         try {
166             return parseList(jsonString, DmaapRequestMessage.class);
167         } catch (Exception e) {
168             sendErrorResponse("Not parsable request received, reason:" + e.toString() + ", input :" + jsonString);
169             throw new ServiceException("Could not parse incomming request. Reason :" + e.getMessage());
170         }
171     }
172
173     protected Iterable<DmaapRequestMessage> fetchAllMessages() throws ServiceException {
174         String topicUrl = this.applicationConfig.getDmaapConsumerTopicUrl();
175         AsyncRestClient consumer = getMessageRouterConsumer();
176         ResponseEntity<String> response = consumer.getForEntity(topicUrl).block();
177         logger.debug("DMaaP consumer received {} : {}", response.getStatusCode(), response.getBody());
178         if (response.getStatusCode().is2xxSuccessful()) {
179             return parseMessages(response.getBody());
180         } else {
181             throw new ServiceException("Cannot fetch because of Error respons: " + response.getStatusCode().toString()
182                     + " " + response.getBody());
183         }
184     }
185
186     private void processMsg(DmaapRequestMessage msg) {
187         logger.debug("Message Reveived from DMAAP : {}", msg);
188         getDmaapMessageHandler().handleDmaapMsg(msg);
189     }
190
191     protected DmaapMessageHandler getDmaapMessageHandler() {
192         if (this.dmaapMessageHandler == null) {
193             String pmsBaseUrl = "http://localhost:" + this.localServerHttpPort;
194             AsyncRestClient pmsClient = restClientFactory.createRestClient(pmsBaseUrl);
195             AsyncRestClient producer =
196                     restClientFactory.createRestClient(this.applicationConfig.getDmaapProducerTopicUrl());
197             this.dmaapMessageHandler = new DmaapMessageHandler(producer, pmsClient);
198         }
199         return this.dmaapMessageHandler;
200     }
201
202     protected void sleep(Duration duration) {
203         try {
204             Thread.sleep(duration.toMillis());
205         } catch (Exception e) {
206             logger.error("Failed to put the thread to sleep", e);
207         }
208     }
209
210     protected AsyncRestClient getMessageRouterConsumer() {
211         return restClientFactory.createRestClient("");
212     }
213
214 }