54dba7a7c35e30aec796506fbb2ddfabcf46fd7d
[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     private String untaggedUrl = null;
103
104     // The pattern for filtering status code
105     private Pattern httpCodeFilterPattern = null;
106
107     @Override
108     public void init(final String consumerName, final EventHandlerParameters consumerParameters,
109         final ApexEventReceiver incomingEventReceiver) throws ApexEventException {
110         this.eventReceiver = incomingEventReceiver;
111         this.name = consumerName;
112
113         // Check and get the REST Properties
114         if (!(consumerParameters
115             .getCarrierTechnologyParameters() instanceof RestRequestorCarrierTechnologyParameters)) {
116             final String errorMessage =
117                 "specified consumer properties are not applicable to REST Requestor consumer (" + this.name + ")";
118             throw new ApexEventException(errorMessage);
119         }
120         restConsumerProperties =
121             (RestRequestorCarrierTechnologyParameters) consumerParameters.getCarrierTechnologyParameters();
122
123         // Check if we are in peered mode
124         if (!consumerParameters.isPeeredMode(EventHandlerPeeredMode.REQUESTOR)) {
125             final String errorMessage = "REST Requestor consumer (" + this.name
126                 + ") must run in peered requestor mode with a REST Requestor producer";
127             throw new ApexEventException(errorMessage);
128         }
129
130         // Check if the HTTP method has been set
131         if (restConsumerProperties.getHttpMethod() == null) {
132             restConsumerProperties
133                 .setHttpMethod(RestRequestorCarrierTechnologyParameters.DEFAULT_REQUESTOR_HTTP_METHOD);
134         }
135
136         // Check if the HTTP URL has been set
137         if (restConsumerProperties.getUrl() == null) {
138             final String errorMessage = "no URL has been specified on REST Requestor consumer (" + this.name + ")";
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             throw new ApexEventException(errorMessage, e);
148         }
149
150         this.httpCodeFilterPattern = Pattern.compile(restConsumerProperties.getHttpCodeFilter());
151
152         // Set the requestor timeout
153         if (consumerParameters.getPeerTimeout(EventHandlerPeeredMode.REQUESTOR) != 0) {
154             restRequestTimeout = consumerParameters.getPeerTimeout(EventHandlerPeeredMode.REQUESTOR);
155         }
156
157         // Check if HTTP headers has been set
158         if (restConsumerProperties.checkHttpHeadersSet()) {
159             final String httpHeaderString = Arrays.deepToString(restConsumerProperties.getHttpHeaders());
160             LOGGER.debug("REST Requestor consumer has http headers ({}): {}", this.name, httpHeaderString);
161         }
162
163         // Initialize the HTTP client
164         client = ClientBuilder.newClient();
165     }
166
167     /**
168      * Receive an incoming REST request from the peered REST Requestor producer and queue it.
169      *
170      * @param restRequest the incoming rest request to queue
171      * @throws ApexEventRuntimeException on queueing errors
172      */
173     public void processRestRequest(final ApexRestRequest restRequest) {
174         // Push the event onto the queue for handling
175         try {
176             incomingRestRequestQueue.add(restRequest);
177         } catch (final Exception requestException) {
178             final String errorMessage =
179                 "could not queue request \"" + restRequest + "\" on REST Requestor consumer (" + this.name + ")";
180             throw new ApexEventRuntimeException(errorMessage);
181         }
182     }
183
184     /**
185      * Get the number of events received to date.
186      *
187      * @return the number of events received
188      */
189     public int getEventsReceived() {
190         return eventsReceived;
191     }
192
193     /**
194      * {@inheritDoc}.
195      */
196     @Override
197     public void run() {
198         // The endless loop that receives events using REST calls
199         while (consumerThread.isAlive() && !stopOrderedFlag) {
200             try {
201                 // Take the next event from the queue
202                 final ApexRestRequest restRequest =
203                     incomingRestRequestQueue.poll(REST_REQUESTOR_WAIT_SLEEP_TIME, TimeUnit.MILLISECONDS);
204                 if (restRequest == null) {
205                     // Poll timed out, check for request timeouts
206                     timeoutExpiredRequests();
207                     continue;
208                 }
209
210                 Properties inputExecutionProperties = restRequest.getExecutionProperties();
211                 untaggedUrl = restConsumerProperties.getUrl();
212                 if (inputExecutionProperties != null) {
213                     Set<String> names = restConsumerProperties.getKeysFromUrl();
214                     Set<String> inputProperty = inputExecutionProperties.stringPropertyNames();
215
216                     names.stream().map(Optional::of)
217                         .forEach(op -> op.filter(inputProperty::contains)
218                             .orElseThrow(() -> new ApexEventRuntimeException(
219                                 "key\"" + op.get() + "\"specified on url \"" + restConsumerProperties.getUrl()
220                                     + "\"not found in execution properties passed by the current policy")));
221
222                     untaggedUrl = names.stream().reduce(untaggedUrl,
223                         (acc, str) -> acc.replace("{" + str + "}", (String) inputExecutionProperties.get(str)));
224                 }
225
226                 // Set the time stamp of the REST request
227                 restRequest.setTimestamp(System.currentTimeMillis());
228
229                 // Create a thread to process the REST request and place it on the map of ongoing
230                 // requests
231                 final RestRequestRunner restRequestRunner = new RestRequestRunner(restRequest);
232                 ongoingRestRequestMap.put(restRequest, restRequestRunner);
233
234                 // Start execution of the request
235                 final Thread restRequestRunnerThread = new Thread(restRequestRunner);
236                 restRequestRunnerThread.setName("RestRequestRunner_" + nextRequestRunnerThreadNo);
237                 restRequestRunnerThread.start();
238             } catch (final InterruptedException e) {
239                 LOGGER.debug("Thread interrupted, Reason {}", e.getMessage());
240                 Thread.currentThread().interrupt();
241             }
242         }
243
244         client.close();
245     }
246
247     /**
248      * This method times out REST requests that have expired.
249      */
250     private void timeoutExpiredRequests() {
251         // Hold a list of timed out requests
252         final List<ApexRestRequest> timedoutRequestList = new ArrayList<>();
253
254         // Check for timeouts
255         for (final Entry<ApexRestRequest, RestRequestRunner> requestEntry : ongoingRestRequestMap.entrySet()) {
256             if (System.currentTimeMillis() - requestEntry.getKey().getTimestamp() > restRequestTimeout) {
257                 requestEntry.getValue().stop();
258                 timedoutRequestList.add(requestEntry.getKey());
259             }
260         }
261
262         // Interrupt timed out requests and remove them from the ongoing map
263         for (final ApexRestRequest timedoutRequest : timedoutRequestList) {
264             final String errorMessage =
265                 "REST Requestor consumer (" + this.name + "), REST request timed out: " + timedoutRequest;
266             LOGGER.warn(errorMessage);
267
268             ongoingRestRequestMap.remove(timedoutRequest);
269         }
270     }
271
272     /**
273      * {@inheritDoc}.
274      */
275     @Override
276     public void stop() {
277         stopOrderedFlag = true;
278
279         while (consumerThread.isAlive()) {
280             ThreadUtilities.sleep(REST_REQUESTOR_WAIT_SLEEP_TIME);
281         }
282     }
283
284     /**
285      * This class is used to start a thread for each request issued.
286      *
287      * @author Liam Fallon (liam.fallon@ericsson.com)
288      */
289     private class RestRequestRunner implements Runnable {
290         private static final String APPLICATION_JSON = "application/json";
291
292         // The REST request being processed by this thread
293         private final ApexRestRequest request;
294
295         // The thread executing the REST request
296         private Thread restRequestThread;
297
298         /**
299          * Constructor, initialise the request runner with the request.
300          *
301          * @param request the request this runner will issue
302          */
303         private RestRequestRunner(final ApexRestRequest request) {
304             this.request = request;
305         }
306
307         /**
308          * {@inheritDoc}.
309          */
310         @Override
311         public void run() {
312             // Get the thread for the request
313             restRequestThread = Thread.currentThread();
314
315             try {
316                 if (restConsumerProperties.getHttpMethod().equals(HttpMethod.PUT)
317                     || restConsumerProperties.getHttpMethod().equals(HttpMethod.POST)) {
318                     NetLoggerUtil.log(EventType.OUT, CommInfrastructure.REST, untaggedUrl,
319                         request.getEvent().toString());
320                 }
321                 // Execute the REST request
322                 final Response response = sendEventAsRestRequest(untaggedUrl);
323                 // Get the event we received
324                 final String eventJsonString = response.readEntity(String.class);
325                 NetLoggerUtil.log(EventType.IN, CommInfrastructure.REST, untaggedUrl, eventJsonString);
326                 // Match the return code
327                 Matcher isPass = httpCodeFilterPattern.matcher(String.valueOf(response.getStatus()));
328
329                 // Check that the request worked
330                 if (!isPass.matches()) {
331                     final String errorMessage = "reception of event from URL \"" + restConsumerProperties.getUrl()
332                         + "\" failed with status code " + response.getStatus();
333                     throw new ApexEventRuntimeException(errorMessage);
334                 }
335
336                 // Check there is content
337                 if (StringUtils.isBlank(eventJsonString)) {
338                     final String errorMessage =
339                         "received an empty response to \"" + request + "\" from URL \"" + untaggedUrl + "\"";
340                     throw new ApexEventRuntimeException(errorMessage);
341                 }
342
343                 // build a key and value property in excutionProperties
344                 Properties executionProperties = new Properties();
345                 executionProperties.put(HTTP_CODE_STATUS, response.getStatus());
346
347                 // Send the event into Apex
348                 eventReceiver.receiveEvent(request.getExecutionId(), executionProperties, eventJsonString);
349
350                 synchronized (eventsReceivedLock) {
351                     eventsReceived++;
352                 }
353             } catch (final Exception e) {
354                 LOGGER.warn("error receiving events on thread {}", consumerThread.getName(), e);
355             } finally {
356                 // Remove the request from the map of ongoing requests
357                 ongoingRestRequestMap.remove(request);
358             }
359         }
360
361         /**
362          * Stop the REST request.
363          */
364         private void stop() {
365             restRequestThread.interrupt();
366         }
367
368         /**
369          * Execute the REST request.
370          *
371          *
372          * @return the response to the REST request
373          */
374         public Response sendEventAsRestRequest(String untaggedUrl) {
375             Builder headers = client.target(untaggedUrl).request(APPLICATION_JSON)
376                 .headers(restConsumerProperties.getHttpHeadersAsMultivaluedMap());
377             switch (restConsumerProperties.getHttpMethod()) {
378                 case GET:
379                     return headers.get();
380
381                 case PUT:
382                     return headers.put(Entity.json(request.getEvent()));
383
384                 case POST:
385                     return headers.post(Entity.json(request.getEvent()));
386
387                 case DELETE:
388                     return headers.delete();
389
390                 default:
391                     break;
392             }
393
394             return null;
395         }
396     }
397 }