c0a43a387fa09331f96db4db661884726f2bcb42
[policy/apex-pdp.git] /
1 /*-
2  * ============LICENSE_START=======================================================
3  *  Copyright (C) 2016-2018 Ericsson. All rights reserved.
4  *  Modifications Copyright (C) 2019-2020 Nordix Foundation.
5  *  Modifications Copyright (C) 2021 Bell Canada. All rights reserved.
6  *  Modifications Copyright (C) 2021 AT&T Intellectual Property. All rights reserved.
7  * ================================================================================
8  * Licensed under the Apache License, Version 2.0 (the "License");
9  * you may not use this file except in compliance with the License.
10  * You may obtain a copy of the License at
11  *
12  *      http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing, software
15  * distributed under the License is distributed on an "AS IS" BASIS,
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * See the License for the specific language governing permissions and
18  * limitations under the License.
19  *
20  * SPDX-License-Identifier: Apache-2.0
21  * ============LICENSE_END=========================================================
22  */
23
24 package org.onap.policy.apex.plugins.event.carrier.restrequestor;
25
26 import java.net.URL;
27 import java.util.ArrayList;
28 import java.util.Arrays;
29 import java.util.List;
30 import java.util.Map;
31 import java.util.Map.Entry;
32 import java.util.Optional;
33 import java.util.Properties;
34 import java.util.Set;
35 import java.util.concurrent.BlockingQueue;
36 import java.util.concurrent.ConcurrentHashMap;
37 import java.util.concurrent.LinkedBlockingQueue;
38 import java.util.concurrent.TimeUnit;
39 import java.util.regex.Matcher;
40 import java.util.regex.Pattern;
41 import javax.ws.rs.client.Client;
42 import javax.ws.rs.client.ClientBuilder;
43 import javax.ws.rs.client.Entity;
44 import javax.ws.rs.client.Invocation.Builder;
45 import javax.ws.rs.core.Response;
46 import lombok.Getter;
47 import org.apache.commons.lang3.StringUtils;
48 import org.onap.policy.apex.core.infrastructure.threading.ThreadUtilities;
49 import org.onap.policy.apex.service.engine.event.ApexEventException;
50 import org.onap.policy.apex.service.engine.event.ApexEventReceiver;
51 import org.onap.policy.apex.service.engine.event.ApexEventRuntimeException;
52 import org.onap.policy.apex.service.engine.event.ApexPluginsEventConsumer;
53 import org.onap.policy.apex.service.parameters.carriertechnology.RestPluginCarrierTechnologyParameters.HttpMethod;
54 import org.onap.policy.apex.service.parameters.eventhandler.EventHandlerParameters;
55 import org.onap.policy.apex.service.parameters.eventhandler.EventHandlerPeeredMode;
56 import org.onap.policy.common.endpoints.event.comm.Topic.CommInfrastructure;
57 import org.onap.policy.common.endpoints.utils.NetLoggerUtil;
58 import org.onap.policy.common.endpoints.utils.NetLoggerUtil.EventType;
59 import org.slf4j.Logger;
60 import org.slf4j.LoggerFactory;
61
62 /**
63  * This class implements an Apex event consumer that issues a REST request and returns the REST response to APEX as an
64  * event.
65  *
66  * @author Liam Fallon (liam.fallon@ericsson.com)
67  */
68 public class ApexRestRequestorConsumer extends ApexPluginsEventConsumer {
69     // Get a reference to the logger
70     private static final Logger LOGGER = LoggerFactory.getLogger(ApexRestRequestorConsumer.class);
71
72     // The amount of time to wait in milliseconds between checks that the consumer thread has
73     // stopped
74     private static final long REST_REQUESTOR_WAIT_SLEEP_TIME = 50;
75
76     // The REST parameters read from the parameter service
77     private RestRequestorCarrierTechnologyParameters restConsumerProperties;
78
79     // The timeout for REST requests
80     private long restRequestTimeout = RestRequestorCarrierTechnologyParameters.DEFAULT_REST_REQUEST_TIMEOUT;
81
82     // The event receiver that will receive events from this consumer
83     private ApexEventReceiver eventReceiver;
84
85     // The HTTP client that makes a REST call to get an input event for Apex
86     private Client client;
87
88     // Temporary request holder for incoming REST requests
89     private final BlockingQueue<ApexRestRequest> incomingRestRequestQueue = new LinkedBlockingQueue<>();
90
91     // Map of ongoing REST request threads indexed by the time they started at
92     private final Map<ApexRestRequest, RestRequestRunner> ongoingRestRequestMap = new ConcurrentHashMap<>();
93
94     // The number of events received to date
95     private Object eventsReceivedLock = new Object();
96     @Getter
97     private int eventsReceived = 0;
98
99     // The number of the next request runner thread
100     private static long nextRequestRunnerThreadNo = 0;
101
102     // The pattern for filtering status code
103     private Pattern httpCodeFilterPattern = null;
104
105     @Override
106     public void init(final String consumerName, final EventHandlerParameters consumerParameters,
107         final ApexEventReceiver incomingEventReceiver) throws ApexEventException {
108         this.eventReceiver = incomingEventReceiver;
109         this.name = consumerName;
110
111         // Check and get the REST Properties
112         if (!(consumerParameters
113             .getCarrierTechnologyParameters() instanceof RestRequestorCarrierTechnologyParameters)) {
114             final String errorMessage =
115                 "specified consumer properties are not applicable to REST Requestor consumer (" + this.name + ")";
116             throw new ApexEventException(errorMessage);
117         }
118         restConsumerProperties =
119             (RestRequestorCarrierTechnologyParameters) consumerParameters.getCarrierTechnologyParameters();
120
121         // Check if we are in peered mode
122         if (!consumerParameters.isPeeredMode(EventHandlerPeeredMode.REQUESTOR)) {
123             final String errorMessage = "REST Requestor consumer (" + this.name
124                 + ") must run in peered requestor mode with a REST Requestor producer";
125             throw new ApexEventException(errorMessage);
126         }
127
128         // Check if the HTTP method has been set
129         if (restConsumerProperties.getHttpMethod() == null) {
130             restConsumerProperties
131                 .setHttpMethod(RestRequestorCarrierTechnologyParameters.DEFAULT_REQUESTOR_HTTP_METHOD);
132         }
133
134         // Check if the HTTP URL has been set
135         if (restConsumerProperties.getUrl() == null) {
136             final String errorMessage = "no URL has been specified on REST Requestor consumer (" + this.name + ")";
137             throw new ApexEventException(errorMessage);
138         }
139
140         // Check if the HTTP URL is valid
141         try {
142             new URL(restConsumerProperties.getUrl());
143         } catch (final Exception e) {
144             final String errorMessage = "invalid URL has been specified on REST Requestor consumer (" + this.name + ")";
145             throw new ApexEventException(errorMessage, e);
146         }
147
148         this.httpCodeFilterPattern = Pattern.compile(restConsumerProperties.getHttpCodeFilter());
149
150         // Set the requestor timeout
151         if (consumerParameters.getPeerTimeout(EventHandlerPeeredMode.REQUESTOR) != 0) {
152             restRequestTimeout = consumerParameters.getPeerTimeout(EventHandlerPeeredMode.REQUESTOR);
153         }
154
155         // Check if HTTP headers has been set
156         if (restConsumerProperties.checkHttpHeadersSet()) {
157             final String httpHeaderString = Arrays.deepToString(restConsumerProperties.getHttpHeaders());
158             LOGGER.debug("REST Requestor consumer has http headers ({}): {}", this.name, httpHeaderString);
159         }
160
161         // Initialize the HTTP client
162         client = ClientBuilder.newClient();
163     }
164
165     /**
166      * Receive an incoming REST request from the peered REST Requestor producer and queue it.
167      *
168      * @param restRequest the incoming rest request to queue
169      * @throws ApexEventRuntimeException on queueing errors
170      */
171     public void processRestRequest(final ApexRestRequest restRequest) {
172         // Push the event onto the queue for handling
173         try {
174             incomingRestRequestQueue.add(restRequest);
175         } catch (final Exception requestException) {
176             final String errorMessage =
177                 "could not queue request \"" + restRequest + "\" on REST Requestor consumer (" + this.name + ")";
178             throw new ApexEventRuntimeException(errorMessage);
179         }
180     }
181
182     /**
183      * {@inheritDoc}.
184      */
185     @Override
186     public void run() {
187         // The endless loop that receives events using REST calls
188         while (consumerThread.isAlive() && !stopOrderedFlag) {
189             try {
190                 // Take the next event from the queue
191                 final ApexRestRequest restRequest =
192                     incomingRestRequestQueue.poll(REST_REQUESTOR_WAIT_SLEEP_TIME, TimeUnit.MILLISECONDS);
193                 if (restRequest == null) {
194                     // Poll timed out, check for request timeouts
195                     timeoutExpiredRequests();
196                     continue;
197                 }
198
199                 // Set the time stamp of the REST request
200                 restRequest.setTimestamp(System.currentTimeMillis());
201
202                 // Create a thread to process the REST request and place it on the map of ongoing
203                 // requests
204                 final RestRequestRunner restRequestRunner = new RestRequestRunner(restRequest);
205                 ongoingRestRequestMap.put(restRequest, restRequestRunner);
206
207                 // Start execution of the request
208                 final Thread restRequestRunnerThread = new Thread(restRequestRunner);
209                 restRequestRunnerThread.setName("RestRequestRunner_" + nextRequestRunnerThreadNo);
210                 restRequestRunnerThread.start();
211             } catch (final InterruptedException e) {
212                 LOGGER.debug("Thread interrupted, Reason {}", e.getMessage());
213                 Thread.currentThread().interrupt();
214             }
215         }
216
217         client.close();
218     }
219
220     /**
221      * This method times out REST requests that have expired.
222      */
223     private void timeoutExpiredRequests() {
224         // Hold a list of timed out requests
225         final List<ApexRestRequest> timedoutRequestList = new ArrayList<>();
226
227         // Check for timeouts
228         for (final Entry<ApexRestRequest, RestRequestRunner> requestEntry : ongoingRestRequestMap.entrySet()) {
229             if (System.currentTimeMillis() - requestEntry.getKey().getTimestamp() > restRequestTimeout) {
230                 requestEntry.getValue().stop();
231                 timedoutRequestList.add(requestEntry.getKey());
232             }
233         }
234
235         // Interrupt timed out requests and remove them from the ongoing map
236         for (final ApexRestRequest timedoutRequest : timedoutRequestList) {
237             final String errorMessage =
238                 "REST Requestor consumer (" + this.name + "), REST request timed out: " + timedoutRequest;
239             LOGGER.warn(errorMessage);
240
241             ongoingRestRequestMap.remove(timedoutRequest);
242         }
243     }
244
245     /**
246      * {@inheritDoc}.
247      */
248     @Override
249     public void stop() {
250         stopOrderedFlag = true;
251
252         while (consumerThread.isAlive()) {
253             ThreadUtilities.sleep(REST_REQUESTOR_WAIT_SLEEP_TIME);
254         }
255     }
256
257     /**
258      * This class is used to start a thread for each request issued.
259      *
260      * @author Liam Fallon (liam.fallon@ericsson.com)
261      */
262     private class RestRequestRunner implements Runnable {
263         private static final String APPLICATION_JSON = "application/json";
264
265         // The REST request being processed by this thread
266         private final ApexRestRequest request;
267
268         // The thread executing the REST request
269         private Thread restRequestThread;
270
271         /**
272          * Constructor, initialise the request runner with the request.
273          *
274          * @param request the request this runner will issue
275          */
276         private RestRequestRunner(final ApexRestRequest request) {
277             this.request = request;
278         }
279
280         /**
281          * {@inheritDoc}.
282          */
283         @Override
284         public void run() {
285             // Get the thread for the request
286             restRequestThread = Thread.currentThread();
287             Properties inputExecutionProperties = request.getExecutionProperties();
288             String url = restConsumerProperties.getUrl();
289             Set<String> names = restConsumerProperties.getKeysFromUrl();
290             if (!names.isEmpty() && inputExecutionProperties != null) {
291                 Set<String> inputProperty = inputExecutionProperties.stringPropertyNames();
292
293                 names.stream().map(Optional::of)
294                     .forEach(op -> op.filter(inputProperty::contains)
295                         .orElseThrow(() -> new ApexEventRuntimeException(
296                             "key\"" + op.get() + "\"specified on url \"" + restConsumerProperties.getUrl()
297                                 + "\"not found in execution properties passed by the current policy")));
298
299                 url = names.stream().reduce(url,
300                     (acc, str) -> acc.replace("{" + str + "}", (String) inputExecutionProperties.get(str)));
301             }
302             try {
303                 if (restConsumerProperties.getHttpMethod().equals(HttpMethod.PUT)
304                     || restConsumerProperties.getHttpMethod().equals(HttpMethod.POST)) {
305                     NetLoggerUtil.log(EventType.OUT, CommInfrastructure.REST, url, request.getEvent().toString());
306                 }
307                 // Execute the REST request
308                 final Response response = sendEventAsRestRequest(url);
309                 // Get the event we received
310                 final String eventJsonString = response.readEntity(String.class);
311                 NetLoggerUtil.log(EventType.IN, CommInfrastructure.REST, url, eventJsonString);
312                 // Match the return code
313                 Matcher isPass = httpCodeFilterPattern.matcher(String.valueOf(response.getStatus()));
314
315                 // Check that the request worked
316                 if (!isPass.matches()) {
317                     final String errorMessage = "reception of event from URL \"" + restConsumerProperties.getUrl()
318                         + "\" failed with status code " + response.getStatus();
319                     throw new ApexEventRuntimeException(errorMessage);
320                 }
321
322                 // Check there is content
323                 if (StringUtils.isBlank(eventJsonString)) {
324                     final String errorMessage =
325                         "received an empty response to \"" + request + "\" from URL \"" + url + "\"";
326                     throw new ApexEventRuntimeException(errorMessage);
327                 }
328
329                 // Send the event into Apex
330                 eventReceiver.receiveEvent(request.getExecutionId(), inputExecutionProperties, eventJsonString);
331
332                 synchronized (eventsReceivedLock) {
333                     eventsReceived++;
334                 }
335             } catch (final Exception e) {
336                 LOGGER.warn("error receiving events on thread {}", consumerThread.getName(), e);
337             } finally {
338                 // Remove the request from the map of ongoing requests
339                 ongoingRestRequestMap.remove(request);
340             }
341         }
342
343         /**
344          * Stop the REST request.
345          */
346         private void stop() {
347             restRequestThread.interrupt();
348         }
349
350         /**
351          * Execute the REST request.
352          *
353          *
354          * @return the response to the REST request
355          */
356         public Response sendEventAsRestRequest(String url) {
357             Builder headers = client.target(url).request(APPLICATION_JSON)
358                 .headers(restConsumerProperties.getHttpHeadersAsMultivaluedMap());
359             switch (restConsumerProperties.getHttpMethod()) {
360                 case GET:
361                     return headers.get();
362
363                 case PUT:
364                     return headers.put(Entity.json(request.getEvent()));
365
366                 case POST:
367                     return headers.post(Entity.json(request.getEvent()));
368
369                 case DELETE:
370                     return headers.delete();
371
372                 default:
373                     break;
374             }
375
376             return null;
377         }
378     }
379 }