0ee621322c05a3ba7a64c3d7142e09e32edc6e8a
[nonrtric.git] / policy-agent / src / main / java / org / oransc / policyagent / dmaap / DmaapMessageConsumer.java
1 /*-
2  * ========================LICENSE_START=================================
3  * O-RAN-SC
4  * %%
5  * Copyright (C) 2020 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.oransc.policyagent.dmaap;
22
23 import com.google.common.collect.Iterables;
24 import com.google.gson.JsonArray;
25 import com.google.gson.JsonElement;
26 import com.google.gson.JsonParser;
27
28 import java.time.Duration;
29 import java.util.ArrayList;
30 import java.util.List;
31
32 import org.oransc.policyagent.clients.AsyncRestClient;
33 import org.oransc.policyagent.configuration.ApplicationConfig;
34 import org.oransc.policyagent.exceptions.ServiceException;
35 import org.slf4j.Logger;
36 import org.slf4j.LoggerFactory;
37 import org.springframework.beans.factory.annotation.Autowired;
38 import org.springframework.beans.factory.annotation.Value;
39 import org.springframework.http.ResponseEntity;
40 import org.springframework.stereotype.Component;
41
42 /**
43  * The class fetches incoming requests from DMAAP. It uses the timeout parameter
44  * that lets the MessageRouter keep the connection with the Kafka open until
45  * requests are sent in.
46  *
47  * <p>
48  * this service will regularly check the configuration and start polling DMaaP
49  * if the configuration is added. If the DMaaP configuration is removed, then
50  * the service will stop polling and resume checking for configuration.
51  *
52  * <p>
53  * Each received request is processed by {@link DmaapMessageHandler}.
54  */
55 @Component
56 public class DmaapMessageConsumer {
57
58     protected static final Duration TIME_BETWEEN_DMAAP_RETRIES = Duration.ofSeconds(10);
59
60     private static final Logger logger = LoggerFactory.getLogger(DmaapMessageConsumer.class);
61
62     private final ApplicationConfig applicationConfig;
63
64     private DmaapMessageHandler dmaapMessageHandler = null;
65
66     @Value("${server.http-port}")
67     private int localServerHttpPort;
68
69     @Autowired
70     public DmaapMessageConsumer(ApplicationConfig applicationConfig) {
71         this.applicationConfig = applicationConfig;
72     }
73
74     /**
75      * Starts the consumer. If there is a DMaaP configuration, it will start polling
76      * for messages. Otherwise it will check regularly for the configuration.
77      *
78      * @return the running thread, for test purposes.
79      */
80     public Thread start() {
81         Thread thread = new Thread(this::messageHandlingLoop);
82         thread.start();
83         return thread;
84     }
85
86     private void messageHandlingLoop() {
87         while (!isStopped()) {
88             try {
89                 if (isDmaapConfigured()) {
90                     Iterable<String> dmaapMsgs = fetchAllMessages();
91                     if (dmaapMsgs != null && Iterables.size(dmaapMsgs) > 0) {
92                         logger.debug("Fetched all the messages from DMAAP and will start to process the messages");
93                         for (String msg : dmaapMsgs) {
94                             processMsg(msg);
95                         }
96                     }
97                 } else {
98                     sleep(TIME_BETWEEN_DMAAP_RETRIES); // wait for configuration
99                 }
100             } catch (Exception e) {
101                 logger.warn("{}", e.getMessage());
102                 sleep(TIME_BETWEEN_DMAAP_RETRIES);
103             }
104         }
105     }
106
107     protected boolean isStopped() {
108         return false;
109     }
110
111     protected boolean isDmaapConfigured() {
112         String producerTopicUrl = applicationConfig.getDmaapProducerTopicUrl();
113         String consumerTopicUrl = applicationConfig.getDmaapConsumerTopicUrl();
114         return (!producerTopicUrl.isEmpty() && !consumerTopicUrl.isEmpty());
115     }
116
117     private static List<String> parseMessages(String jsonString) {
118         JsonArray arrayOfMessages = JsonParser.parseString(jsonString).getAsJsonArray();
119         List<String> result = new ArrayList<>();
120         for (JsonElement element : arrayOfMessages) {
121             if (element.isJsonPrimitive()) {
122                 result.add(element.getAsString());
123             } else {
124                 String messageAsString = element.toString();
125                 result.add(messageAsString);
126             }
127         }
128         return result;
129     }
130
131     protected Iterable<String> fetchAllMessages() throws ServiceException {
132         String topicUrl = this.applicationConfig.getDmaapConsumerTopicUrl();
133         AsyncRestClient consumer = getMessageRouterConsumer();
134         ResponseEntity<String> response = consumer.getForEntity(topicUrl).block();
135         logger.debug("DMaaP consumer received {} : {}", response.getStatusCode(), response.getBody());
136         if (response.getStatusCode().is2xxSuccessful()) {
137             return parseMessages(response.getBody());
138         } else {
139             throw new ServiceException("Cannot fetch because of Error respons: " + response.getStatusCode().toString()
140                 + " " + response.getBody());
141         }
142     }
143
144     private void processMsg(String msg) {
145         logger.debug("Message Reveived from DMAAP : {}", msg);
146         getDmaapMessageHandler().handleDmaapMsg(msg);
147     }
148
149     protected DmaapMessageHandler getDmaapMessageHandler() {
150         if (this.dmaapMessageHandler == null) {
151             String agentBaseUrl = "http://localhost:" + this.localServerHttpPort;
152             AsyncRestClient agentClient =
153                 new AsyncRestClient(agentBaseUrl, this.applicationConfig.getWebClientConfig());
154             AsyncRestClient producer = new AsyncRestClient(this.applicationConfig.getDmaapProducerTopicUrl(),
155                 this.applicationConfig.getWebClientConfig());
156             this.dmaapMessageHandler = new DmaapMessageHandler(producer, agentClient);
157         }
158         return this.dmaapMessageHandler;
159     }
160
161     protected void sleep(Duration duration) {
162         try {
163             Thread.sleep(duration.toMillis());
164         } catch (Exception e) {
165             logger.error("Failed to put the thread to sleep", e);
166         }
167     }
168
169     protected AsyncRestClient getMessageRouterConsumer() {
170         return new AsyncRestClient("", this.applicationConfig.getWebClientConfig());
171     }
172
173 }