d7ee0a5ee7304454220c40a94fe0293434892727
[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 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     // Temporary request holder for incoming REST requests
90     private final BlockingQueue<ApexRestRequest> incomingRestRequestQueue = new LinkedBlockingQueue<>();
91
92     // Map of ongoing REST request threads indexed by the time they started at
93     private final Map<ApexRestRequest, RestRequestRunner> ongoingRestRequestMap = new ConcurrentHashMap<>();
94
95     // The number of events received to date
96     private Object eventsReceivedLock = new Object();
97     private Integer 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      * Get the number of events received to date.
184      *
185      * @return the number of events received
186      */
187     public int getEventsReceived() {
188         return eventsReceived;
189     }
190
191     /**
192      * {@inheritDoc}.
193      */
194     @Override
195     public void run() {
196         // The endless loop that receives events using REST calls
197         while (consumerThread.isAlive() && !stopOrderedFlag) {
198             try {
199                 // Take the next event from the queue
200                 final ApexRestRequest restRequest =
201                     incomingRestRequestQueue.poll(REST_REQUESTOR_WAIT_SLEEP_TIME, TimeUnit.MILLISECONDS);
202                 if (restRequest == null) {
203                     // Poll timed out, check for request timeouts
204                     timeoutExpiredRequests();
205                     continue;
206                 }
207
208                 // Set the time stamp of the REST request
209                 restRequest.setTimestamp(System.currentTimeMillis());
210
211                 // Create a thread to process the REST request and place it on the map of ongoing
212                 // requests
213                 final RestRequestRunner restRequestRunner = new RestRequestRunner(restRequest);
214                 ongoingRestRequestMap.put(restRequest, restRequestRunner);
215
216                 // Start execution of the request
217                 final Thread restRequestRunnerThread = new Thread(restRequestRunner);
218                 restRequestRunnerThread.setName("RestRequestRunner_" + nextRequestRunnerThreadNo);
219                 restRequestRunnerThread.start();
220             } catch (final InterruptedException e) {
221                 LOGGER.debug("Thread interrupted, Reason {}", e.getMessage());
222                 Thread.currentThread().interrupt();
223             }
224         }
225
226         client.close();
227     }
228
229     /**
230      * This method times out REST requests that have expired.
231      */
232     private void timeoutExpiredRequests() {
233         // Hold a list of timed out requests
234         final List<ApexRestRequest> timedoutRequestList = new ArrayList<>();
235
236         // Check for timeouts
237         for (final Entry<ApexRestRequest, RestRequestRunner> requestEntry : ongoingRestRequestMap.entrySet()) {
238             if (System.currentTimeMillis() - requestEntry.getKey().getTimestamp() > restRequestTimeout) {
239                 requestEntry.getValue().stop();
240                 timedoutRequestList.add(requestEntry.getKey());
241             }
242         }
243
244         // Interrupt timed out requests and remove them from the ongoing map
245         for (final ApexRestRequest timedoutRequest : timedoutRequestList) {
246             final String errorMessage =
247                 "REST Requestor consumer (" + this.name + "), REST request timed out: " + timedoutRequest;
248             LOGGER.warn(errorMessage);
249
250             ongoingRestRequestMap.remove(timedoutRequest);
251         }
252     }
253
254     /**
255      * {@inheritDoc}.
256      */
257     @Override
258     public void stop() {
259         stopOrderedFlag = true;
260
261         while (consumerThread.isAlive()) {
262             ThreadUtilities.sleep(REST_REQUESTOR_WAIT_SLEEP_TIME);
263         }
264     }
265
266     /**
267      * This class is used to start a thread for each request issued.
268      *
269      * @author Liam Fallon (liam.fallon@ericsson.com)
270      */
271     private class RestRequestRunner implements Runnable {
272         private static final String APPLICATION_JSON = "application/json";
273
274         // The REST request being processed by this thread
275         private final ApexRestRequest request;
276
277         // The thread executing the REST request
278         private Thread restRequestThread;
279
280         /**
281          * Constructor, initialise the request runner with the request.
282          *
283          * @param request the request this runner will issue
284          */
285         private RestRequestRunner(final ApexRestRequest request) {
286             this.request = request;
287         }
288
289         /**
290          * {@inheritDoc}.
291          */
292         @Override
293         public void run() {
294             // Get the thread for the request
295             restRequestThread = Thread.currentThread();
296             Properties inputExecutionProperties = request.getExecutionProperties();
297             String url = restConsumerProperties.getUrl();
298             Set<String> names = restConsumerProperties.getKeysFromUrl();
299             if (!names.isEmpty() && inputExecutionProperties != null) {
300                 Set<String> inputProperty = inputExecutionProperties.stringPropertyNames();
301
302                 names.stream().map(Optional::of)
303                     .forEach(op -> op.filter(inputProperty::contains)
304                         .orElseThrow(() -> new ApexEventRuntimeException(
305                             "key\"" + op.get() + "\"specified on url \"" + restConsumerProperties.getUrl()
306                                 + "\"not found in execution properties passed by the current policy")));
307
308                 url = names.stream().reduce(url,
309                     (acc, str) -> acc.replace("{" + str + "}", (String) inputExecutionProperties.get(str)));
310             }
311             try {
312                 if (restConsumerProperties.getHttpMethod().equals(HttpMethod.PUT)
313                     || restConsumerProperties.getHttpMethod().equals(HttpMethod.POST)) {
314                     NetLoggerUtil.log(EventType.OUT, CommInfrastructure.REST, url, request.getEvent().toString());
315                 }
316                 // Execute the REST request
317                 final Response response = sendEventAsRestRequest(url);
318                 // Get the event we received
319                 final String eventJsonString = response.readEntity(String.class);
320                 NetLoggerUtil.log(EventType.IN, CommInfrastructure.REST, url, eventJsonString);
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();
328                     throw new ApexEventRuntimeException(errorMessage);
329                 }
330
331                 // Check there is content
332                 if (StringUtils.isBlank(eventJsonString)) {
333                     final String errorMessage =
334                         "received an empty response to \"" + request + "\" from URL \"" + url + "\"";
335                     throw new ApexEventRuntimeException(errorMessage);
336                 }
337
338                 // build a key and value property in excutionProperties
339                 Properties executionProperties = new Properties();
340                 executionProperties.put(HTTP_CODE_STATUS, response.getStatus());
341
342                 // Send the event into Apex
343                 eventReceiver.receiveEvent(request.getExecutionId(), executionProperties, eventJsonString);
344
345                 synchronized (eventsReceivedLock) {
346                     eventsReceived++;
347                 }
348             } catch (final Exception e) {
349                 LOGGER.warn("error receiving events on thread {}", consumerThread.getName(), e);
350             } finally {
351                 // Remove the request from the map of ongoing requests
352                 ongoingRestRequestMap.remove(request);
353             }
354         }
355
356         /**
357          * Stop the REST request.
358          */
359         private void stop() {
360             restRequestThread.interrupt();
361         }
362
363         /**
364          * Execute the REST request.
365          *
366          *
367          * @return the response to the REST request
368          */
369         public Response sendEventAsRestRequest(String url) {
370             Builder headers = client.target(url).request(APPLICATION_JSON)
371                 .headers(restConsumerProperties.getHttpHeadersAsMultivaluedMap());
372             switch (restConsumerProperties.getHttpMethod()) {
373                 case GET:
374                     return headers.get();
375
376                 case PUT:
377                     return headers.put(Entity.json(request.getEvent()));
378
379                 case POST:
380                     return headers.post(Entity.json(request.getEvent()));
381
382                 case DELETE:
383                     return headers.delete();
384
385                 default:
386                     break;
387             }
388
389             return null;
390         }
391     }
392 }