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