f60abc24c5b57ad046c092ddead2afee66d92cb7
[policy/apex-pdp.git] /
1 /*-
2  * ============LICENSE_START=======================================================
3  *  Copyright (C) 2016-2018 Ericsson. All rights reserved.
4  *  Modifications Copyright (C) 2019 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.EnumMap;
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
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
47 import org.apache.commons.lang3.StringUtils;
48 import org.onap.policy.apex.core.infrastructure.threading.ApplicationThreadFactory;
49 import org.onap.policy.apex.core.infrastructure.threading.ThreadUtilities;
50 import org.onap.policy.apex.service.engine.event.ApexEventConsumer;
51 import org.onap.policy.apex.service.engine.event.ApexEventException;
52 import org.onap.policy.apex.service.engine.event.ApexEventReceiver;
53 import org.onap.policy.apex.service.engine.event.ApexEventRuntimeException;
54 import org.onap.policy.apex.service.engine.event.PeeredReference;
55 import org.onap.policy.apex.service.parameters.eventhandler.EventHandlerParameters;
56 import org.onap.policy.apex.service.parameters.eventhandler.EventHandlerPeeredMode;
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 implements ApexEventConsumer, Runnable {
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 Key for property
75     private static final String HTTP_CODE_STATUS = "HTTP_CODE_STATUS";
76
77     // The REST parameters read from the parameter service
78     private RestRequestorCarrierTechnologyParameters restConsumerProperties;
79
80     // The timeout for REST requests
81     private long restRequestTimeout = RestRequestorCarrierTechnologyParameters.DEFAULT_REST_REQUEST_TIMEOUT;
82
83     // The event receiver that will receive events from this consumer
84     private ApexEventReceiver eventReceiver;
85
86     // The HTTP client that makes a REST call to get an input event for Apex
87     private Client client;
88
89     // The name for this consumer
90     private String name = null;
91
92     // The peer references for this event handler
93     private Map<EventHandlerPeeredMode, PeeredReference> peerReferenceMap = new EnumMap<>(EventHandlerPeeredMode.class);
94
95     // The consumer thread and stopping flag
96     private Thread consumerThread;
97     private boolean stopOrderedFlag = false;
98
99     // Temporary request holder for incoming REST requests
100     private final BlockingQueue<ApexRestRequest> incomingRestRequestQueue = new LinkedBlockingQueue<>();
101
102     // Map of ongoing REST request threads indexed by the time they started at
103     private final Map<ApexRestRequest, RestRequestRunner> ongoingRestRequestMap = new ConcurrentHashMap<>();
104
105     // The number of events received to date
106     private Object eventsReceivedLock = new Object();
107     private Integer eventsReceived = 0;
108
109     // The number of the next request runner thread
110     private static long nextRequestRunnerThreadNo = 0;
111
112     private String untaggedUrl = null;
113
114     // The pattern for filtering status code
115     private Pattern httpCodeFilterPattern = null;
116
117     @Override
118     public void init(final String consumerName, final EventHandlerParameters consumerParameters,
119             final ApexEventReceiver incomingEventReceiver) throws ApexEventException {
120         this.eventReceiver = incomingEventReceiver;
121         this.name = consumerName;
122
123         // Check and get the REST Properties
124         if (!(consumerParameters
125                 .getCarrierTechnologyParameters() instanceof RestRequestorCarrierTechnologyParameters)) {
126             final String errorMessage =
127                     "specified consumer properties are not applicable to REST Requestor consumer (" + this.name + ")";
128             LOGGER.warn(errorMessage);
129             throw new ApexEventException(errorMessage);
130         }
131         restConsumerProperties =
132                 (RestRequestorCarrierTechnologyParameters) consumerParameters.getCarrierTechnologyParameters();
133
134         // Check if we are in peered mode
135         if (!consumerParameters.isPeeredMode(EventHandlerPeeredMode.REQUESTOR)) {
136             final String errorMessage = "REST Requestor consumer (" + this.name
137                     + ") must run in peered requestor mode with a REST Requestor producer";
138             LOGGER.warn(errorMessage);
139             throw new ApexEventException(errorMessage);
140         }
141
142         // Check if the HTTP method has been set
143         if (restConsumerProperties.getHttpMethod() == null) {
144             restConsumerProperties
145                     .setHttpMethod(RestRequestorCarrierTechnologyParameters.DEFAULT_REQUESTOR_HTTP_METHOD);
146         }
147
148         // Check if the HTTP URL has been set
149         if (restConsumerProperties.getUrl() == null) {
150             final String errorMessage = "no URL has been specified on REST Requestor consumer (" + this.name + ")";
151             LOGGER.warn(errorMessage);
152             throw new ApexEventException(errorMessage);
153         }
154
155         // Check if the HTTP URL is valid
156         try {
157             new URL(restConsumerProperties.getUrl());
158         } catch (final Exception e) {
159             final String errorMessage = "invalid URL has been specified on REST Requestor consumer (" + this.name + ")";
160             LOGGER.warn(errorMessage);
161             throw new ApexEventException(errorMessage, e);
162         }
163
164         this.httpCodeFilterPattern = Pattern.compile(restConsumerProperties.getHttpCodeFilter());
165
166         // Set the requestor timeout
167         if (consumerParameters.getPeerTimeout(EventHandlerPeeredMode.REQUESTOR) != 0) {
168             restRequestTimeout = consumerParameters.getPeerTimeout(EventHandlerPeeredMode.REQUESTOR);
169         }
170
171         // Check if HTTP headers has been set
172         if (restConsumerProperties.checkHttpHeadersSet()) {
173             LOGGER.debug("REST Requestor consumer has http headers ({}): {}", this.name,
174                     Arrays.deepToString(restConsumerProperties.getHttpHeaders()));
175         }
176
177         // Initialize the HTTP client
178         client = ClientBuilder.newClient();
179     }
180
181     /**
182      * Receive an incoming REST request from the peered REST Requestor producer and queue it.
183      *
184      * @param restRequest the incoming rest request to queue
185      * @throws ApexEventRuntimeException on queueing errors
186      */
187     public void processRestRequest(final ApexRestRequest restRequest) {
188         // Push the event onto the queue for handling
189         try {
190             incomingRestRequestQueue.add(restRequest);
191         } catch (final Exception requestException) {
192             final String errorMessage =
193                     "could not queue request \"" + restRequest + "\" on REST Requestor consumer (" + this.name + ")";
194             LOGGER.warn(errorMessage, requestException);
195             throw new ApexEventRuntimeException(errorMessage);
196         }
197     }
198
199     /**
200      * {@inheritDoc}.
201      */
202     @Override
203     public void start() {
204         // Configure and start the event reception thread
205         final String threadName = this.getClass().getName() + ":" + this.name;
206         consumerThread = new ApplicationThreadFactory(threadName).newThread(this);
207         consumerThread.setDaemon(true);
208         consumerThread.start();
209     }
210
211     /**
212      * {@inheritDoc}.
213      */
214     @Override
215     public String getName() {
216         return name;
217     }
218
219     /**
220      * Get the number of events received to date.
221      *
222      * @return the number of events received
223      */
224     public int getEventsReceived() {
225         return eventsReceived;
226     }
227
228     /**
229      * {@inheritDoc}.
230      */
231     @Override
232     public PeeredReference getPeeredReference(final EventHandlerPeeredMode peeredMode) {
233         return peerReferenceMap.get(peeredMode);
234     }
235
236     /**
237      * {@inheritDoc}.
238      */
239     @Override
240     public void setPeeredReference(final EventHandlerPeeredMode peeredMode, final PeeredReference peeredReference) {
241         peerReferenceMap.put(peeredMode, peeredReference);
242     }
243
244     /**
245      * {@inheritDoc}.
246      */
247     @Override
248     public void run() {
249         // The endless loop that receives events using REST calls
250         while (consumerThread.isAlive() && !stopOrderedFlag) {
251             try {
252                 // Take the next event from the queue
253                 final ApexRestRequest restRequest =
254                         incomingRestRequestQueue.poll(REST_REQUESTOR_WAIT_SLEEP_TIME, TimeUnit.MILLISECONDS);
255                 if (restRequest == null) {
256                     // Poll timed out, check for request timeouts
257                     timeoutExpiredRequests();
258                     continue;
259                 }
260
261                 Properties inputExecutionProperties = restRequest.getExecutionProperties();
262                 untaggedUrl = restConsumerProperties.getUrl();
263                 if (inputExecutionProperties != null) {
264                     Set<String> names = restConsumerProperties.getKeysFromUrl();
265                     Set<String> inputProperty = inputExecutionProperties.stringPropertyNames();
266
267                     names.stream().map(Optional::of).forEach(op ->
268                         op.filter(inputProperty::contains)
269                                 .orElseThrow(() -> new ApexEventRuntimeException(
270                                         "key\"" + op.get() + "\"specified on url \"" + restConsumerProperties.getUrl()
271                                                 + "\"not found in execution properties passed by the current policy")));
272
273                     untaggedUrl = names.stream().reduce(untaggedUrl,
274                         (acc, str) -> acc.replace("{" + str + "}", (String) inputExecutionProperties.get(str)));
275                 }
276
277                 // Set the time stamp of the REST request
278                 restRequest.setTimestamp(System.currentTimeMillis());
279
280                 // Create a thread to process the REST request and place it on the map of ongoing
281                 // requests
282                 final RestRequestRunner restRequestRunner = new RestRequestRunner(restRequest);
283                 ongoingRestRequestMap.put(restRequest, restRequestRunner);
284
285                 // Start execution of the request
286                 final Thread restRequestRunnerThread = new Thread(restRequestRunner);
287                 restRequestRunnerThread.setName("RestRequestRunner_" + nextRequestRunnerThreadNo);
288                 restRequestRunnerThread.start();
289             } catch (final InterruptedException e) {
290                 LOGGER.debug("Thread interrupted, Reason {}", e.getMessage());
291                 Thread.currentThread().interrupt();
292             }
293         }
294
295         client.close();
296     }
297
298     /**
299      * This method times out REST requests that have expired.
300      */
301     private void timeoutExpiredRequests() {
302         // Hold a list of timed out requests
303         final List<ApexRestRequest> timedoutRequestList = new ArrayList<>();
304
305         // Check for timeouts
306         for (final Entry<ApexRestRequest, RestRequestRunner> requestEntry : ongoingRestRequestMap.entrySet()) {
307             if (System.currentTimeMillis() - requestEntry.getKey().getTimestamp() > restRequestTimeout) {
308                 requestEntry.getValue().stop();
309                 timedoutRequestList.add(requestEntry.getKey());
310             }
311         }
312
313         // Interrupt timed out requests and remove them from the ongoing map
314         for (final ApexRestRequest timedoutRequest : timedoutRequestList) {
315             final String errorMessage =
316                     "REST Requestor consumer (" + this.name + "), REST request timed out: " + timedoutRequest;
317             LOGGER.warn(errorMessage);
318
319             ongoingRestRequestMap.remove(timedoutRequest);
320         }
321     }
322
323     /**
324      * {@inheritDoc}.
325      */
326     @Override
327     public void stop() {
328         stopOrderedFlag = true;
329
330         while (consumerThread.isAlive()) {
331             ThreadUtilities.sleep(REST_REQUESTOR_WAIT_SLEEP_TIME);
332         }
333     }
334
335     /**
336      * This class is used to start a thread for each request issued.
337      *
338      * @author Liam Fallon (liam.fallon@ericsson.com)
339      */
340     private class RestRequestRunner implements Runnable {
341         private static final String APPLICATION_JSON = "application/json";
342
343         // The REST request being processed by this thread
344         private final ApexRestRequest request;
345
346         // The thread executing the REST request
347         private Thread restRequestThread;
348
349         /**
350          * Constructor, initialise the request runner with the request.
351          *
352          * @param request the request this runner will issue
353          */
354         private RestRequestRunner(final ApexRestRequest request) {
355             this.request = request;
356         }
357
358         /**
359          * {@inheritDoc}.
360          */
361         @Override
362         public void run() {
363             // Get the thread for the request
364             restRequestThread = Thread.currentThread();
365
366             try {
367                 // Execute the REST request
368                 final Response response = sendEventAsRestRequest(untaggedUrl);
369
370                 // Match the return code
371                 Matcher isPass = httpCodeFilterPattern.matcher(String.valueOf(response.getStatus()));
372
373                 // Check that the request worked
374                 if (!isPass.matches()) {
375                     final String errorMessage ="reception of event from URL \"" + restConsumerProperties.getUrl()
376                             + "\" failed with status code " + response.getStatus() + " and message \""
377                             + response.readEntity(String.class) + "\"";
378                     throw new ApexEventRuntimeException(errorMessage);
379                 }
380
381                 // Get the event we received
382                 final String eventJsonString = response.readEntity(String.class);
383
384                 // Check there is content
385                 if (StringUtils.isBlank(eventJsonString)) {
386                     final String errorMessage =
387                             "received an empty response to \"" + request + "\" from URL \"" + untaggedUrl + "\"";
388                     throw new ApexEventRuntimeException(errorMessage);
389                 }
390
391                 // build a key and value property in excutionProperties
392                 Properties executionProperties = new Properties();
393                 executionProperties.put(HTTP_CODE_STATUS, response.getStatus());
394
395                 // Send the event into Apex
396                 eventReceiver.receiveEvent(request.getExecutionId(), executionProperties, eventJsonString);
397
398                 synchronized (eventsReceivedLock) {
399                     eventsReceived++;
400                 }
401             } catch (final Exception e) {
402                 LOGGER.warn("error receiving events on thread {}", consumerThread.getName(), e);
403             } finally {
404                 // Remove the request from the map of ongoing requests
405                 ongoingRestRequestMap.remove(request);
406             }
407         }
408
409         /**
410          * Stop the REST request.
411          */
412         private void stop() {
413             restRequestThread.interrupt();
414         }
415
416         /**
417          * Execute the REST request.
418          *
419          *
420          * @return the response to the REST request
421          */
422         public Response sendEventAsRestRequest(String untaggedUrl) {
423             Builder headers = client.target(untaggedUrl).request(APPLICATION_JSON)
424                     .headers(restConsumerProperties.getHttpHeadersAsMultivaluedMap());
425             switch (restConsumerProperties.getHttpMethod()) {
426                 case GET:
427                     return headers.get();
428
429                 case PUT:
430                     return headers.put(Entity.json(request.getEvent()));
431
432                 case POST:
433                     return headers.post(Entity.json(request.getEvent()));
434
435                 case DELETE:
436                     return headers.delete();
437
438                 default:
439                     break;
440             }
441
442             return null;
443         }
444     }
445 }