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