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