Merge "Update mrstub with nginx"
[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
25 import java.io.IOException;
26 import java.time.Duration;
27 import java.util.Properties;
28
29 import org.onap.dmaap.mr.client.MRBatchingPublisher;
30 import org.onap.dmaap.mr.client.MRClientFactory;
31 import org.onap.dmaap.mr.client.MRConsumer;
32 import org.onap.dmaap.mr.client.response.MRConsumerResponse;
33 import org.oransc.policyagent.clients.AsyncRestClient;
34 import org.oransc.policyagent.configuration.ApplicationConfig;
35 import org.oransc.policyagent.exceptions.ServiceException;
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.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     private MRConsumer messageRouterConsumer = null;
66
67     @Value("${server.port}")
68     private int localServerPort;
69
70     @Autowired
71     public DmaapMessageConsumer(ApplicationConfig applicationConfig) {
72         this.applicationConfig = applicationConfig;
73     }
74
75     /**
76      * Starts the consumer. If there is a DMaaP configuration, it will start polling
77      * for messages. Otherwise it will check regularly for the configuration.
78      *
79      * @return the running thread, for test purposes.
80      */
81     public Thread start() {
82         Thread thread = new Thread(this::messageHandlingLoop);
83         thread.start();
84         return thread;
85     }
86
87     private void messageHandlingLoop() {
88         while (!isStopped()) {
89             try {
90                 if (isDmaapConfigured()) {
91                     Iterable<String> dmaapMsgs = fetchAllMessages();
92                     if (dmaapMsgs != null && Iterables.size(dmaapMsgs) > 0) {
93                         logger.debug("Fetched all the messages from DMAAP and will start to process the messages");
94                         for (String msg : dmaapMsgs) {
95                             processMsg(msg);
96                         }
97                     }
98                 } else {
99                     sleep(TIME_BETWEEN_DMAAP_RETRIES); // wait for configuration
100                 }
101             } catch (Exception e) {
102                 logger.warn("Cannot fetch because of {}", e.getMessage());
103                 sleep(TIME_BETWEEN_DMAAP_RETRIES);
104             }
105         }
106     }
107
108     protected boolean isStopped() {
109         return false;
110     }
111
112     protected boolean isDmaapConfigured() {
113         Properties consumerCfg = applicationConfig.getDmaapConsumerConfig();
114         Properties producerCfg = applicationConfig.getDmaapPublisherConfig();
115         return (consumerCfg != null && consumerCfg.size() > 0 && producerCfg != null && producerCfg.size() > 0);
116     }
117
118     protected Iterable<String> fetchAllMessages() throws ServiceException, IOException {
119         Properties dmaapConsumerProperties = this.applicationConfig.getDmaapConsumerConfig();
120         MRConsumer consumer = getMessageRouterConsumer(dmaapConsumerProperties);
121         MRConsumerResponse response = consumer.fetchWithReturnConsumerResponse();
122         if (response == null || !"200".equals(response.getResponseCode())) {
123             String errorMessage = "DMaaP NULL response received";
124             if (response != null) {
125                 errorMessage = "Error respons " + response.getResponseCode() + " " + response.getResponseMessage()
126                     + " from DMaaP.";
127             }
128             throw new ServiceException(errorMessage);
129         } else {
130             logger.debug("DMaaP consumer received {} : {}", response.getResponseCode(), response.getResponseMessage());
131             return response.getActualMessages();
132         }
133     }
134
135     private void processMsg(String msg) throws IOException {
136         logger.debug("Message Reveived from DMAAP : {}", msg);
137         getDmaapMessageHandler().handleDmaapMsg(msg);
138     }
139
140     protected DmaapMessageHandler getDmaapMessageHandler() throws IOException {
141         if (this.dmaapMessageHandler == null) {
142             String agentBaseUrl = "https://localhost:" + this.localServerPort;
143             AsyncRestClient agentClient = new AsyncRestClient(agentBaseUrl);
144             Properties dmaapPublisherProperties = applicationConfig.getDmaapPublisherConfig();
145             MRBatchingPublisher producer = MRClientFactory.createBatchingPublisher(dmaapPublisherProperties);
146             this.dmaapMessageHandler = new DmaapMessageHandler(producer, agentClient);
147         }
148         return this.dmaapMessageHandler;
149     }
150
151     protected void sleep(Duration duration) {
152         try {
153             Thread.sleep(duration.toMillis());
154         } catch (Exception e) {
155             logger.error("Failed to put the thread to sleep", e);
156         }
157     }
158
159     protected MRConsumer getMessageRouterConsumer(Properties dmaapConsumerProperties) throws IOException {
160         if (this.messageRouterConsumer == null) {
161             this.messageRouterConsumer = MRClientFactory.createConsumer(dmaapConsumerProperties);
162         }
163         return this.messageRouterConsumer;
164     }
165
166 }