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
10 * http://www.apache.org/licenses/LICENSE-2.0
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.
18 * SPDX-License-Identifier: Apache-2.0
19 * ============LICENSE_END=========================================================
22 package org.onap.policy.apex.plugins.event.carrier.restrequestor;
25 import java.util.ArrayList;
26 import java.util.Arrays;
27 import java.util.List;
29 import java.util.Map.Entry;
30 import java.util.Optional;
31 import java.util.Properties;
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 import java.util.regex.Matcher;
38 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;
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;
58 * This class implements an Apex event consumer that issues a REST request and returns the REST response to APEX as an
61 * @author Liam Fallon (liam.fallon@ericsson.com)
63 public class ApexRestRequestorConsumer extends ApexPluginsEventConsumer {
64 // Get a reference to the logger
65 private static final Logger LOGGER = LoggerFactory.getLogger(ApexRestRequestorConsumer.class);
67 // The amount of time to wait in milliseconds between checks that the consumer thread has
69 private static final long REST_REQUESTOR_WAIT_SLEEP_TIME = 50;
71 // The Key for property
72 private static final String HTTP_CODE_STATUS = "HTTP_CODE_STATUS";
74 // The REST parameters read from the parameter service
75 private RestRequestorCarrierTechnologyParameters restConsumerProperties;
77 // The timeout for REST requests
78 private long restRequestTimeout = RestRequestorCarrierTechnologyParameters.DEFAULT_REST_REQUEST_TIMEOUT;
80 // The event receiver that will receive events from this consumer
81 private ApexEventReceiver eventReceiver;
83 // The HTTP client that makes a REST call to get an input event for Apex
84 private Client client;
86 // Temporary request holder for incoming REST requests
87 private final BlockingQueue<ApexRestRequest> incomingRestRequestQueue = new LinkedBlockingQueue<>();
89 // Map of ongoing REST request threads indexed by the time they started at
90 private final Map<ApexRestRequest, RestRequestRunner> ongoingRestRequestMap = new ConcurrentHashMap<>();
92 // The number of events received to date
93 private Object eventsReceivedLock = new Object();
94 private Integer eventsReceived = 0;
96 // The number of the next request runner thread
97 private static long nextRequestRunnerThreadNo = 0;
99 private String untaggedUrl = null;
101 // The pattern for filtering status code
102 private Pattern httpCodeFilterPattern = null;
105 public void init(final String consumerName, final EventHandlerParameters consumerParameters,
106 final ApexEventReceiver incomingEventReceiver) throws ApexEventException {
107 this.eventReceiver = incomingEventReceiver;
108 this.name = consumerName;
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 throw new ApexEventException(errorMessage);
117 restConsumerProperties =
118 (RestRequestorCarrierTechnologyParameters) consumerParameters.getCarrierTechnologyParameters();
120 // Check if we are in peered mode
121 if (!consumerParameters.isPeeredMode(EventHandlerPeeredMode.REQUESTOR)) {
122 final String errorMessage = "REST Requestor consumer (" + this.name
123 + ") must run in peered requestor mode with a REST Requestor producer";
124 throw new ApexEventException(errorMessage);
127 // Check if the HTTP method has been set
128 if (restConsumerProperties.getHttpMethod() == null) {
129 restConsumerProperties
130 .setHttpMethod(RestRequestorCarrierTechnologyParameters.DEFAULT_REQUESTOR_HTTP_METHOD);
133 // Check if the HTTP URL has been set
134 if (restConsumerProperties.getUrl() == null) {
135 final String errorMessage = "no URL has been specified on REST Requestor consumer (" + this.name + ")";
136 throw new ApexEventException(errorMessage);
139 // Check if the HTTP URL is valid
141 new URL(restConsumerProperties.getUrl());
142 } catch (final Exception e) {
143 final String errorMessage = "invalid URL has been specified on REST Requestor consumer (" + this.name + ")";
144 throw new ApexEventException(errorMessage, e);
147 this.httpCodeFilterPattern = Pattern.compile(restConsumerProperties.getHttpCodeFilter());
149 // Set the requestor timeout
150 if (consumerParameters.getPeerTimeout(EventHandlerPeeredMode.REQUESTOR) != 0) {
151 restRequestTimeout = consumerParameters.getPeerTimeout(EventHandlerPeeredMode.REQUESTOR);
154 // Check if HTTP headers has been set
155 if (restConsumerProperties.checkHttpHeadersSet()) {
156 final String httpHeaderString = Arrays.deepToString(restConsumerProperties.getHttpHeaders());
157 LOGGER.debug("REST Requestor consumer has http headers ({}): {}", this.name, httpHeaderString);
160 // Initialize the HTTP client
161 client = ClientBuilder.newClient();
165 * Receive an incoming REST request from the peered REST Requestor producer and queue it.
167 * @param restRequest the incoming rest request to queue
168 * @throws ApexEventRuntimeException on queueing errors
170 public void processRestRequest(final ApexRestRequest restRequest) {
171 // Push the event onto the queue for handling
173 incomingRestRequestQueue.add(restRequest);
174 } catch (final Exception requestException) {
175 final String errorMessage =
176 "could not queue request \"" + restRequest + "\" on REST Requestor consumer (" + this.name + ")";
177 throw new ApexEventRuntimeException(errorMessage);
182 * Get the number of events received to date.
184 * @return the number of events received
186 public int getEventsReceived() {
187 return eventsReceived;
195 // The endless loop that receives events using REST calls
196 while (consumerThread.isAlive() && !stopOrderedFlag) {
198 // Take the next event from the queue
199 final ApexRestRequest restRequest =
200 incomingRestRequestQueue.poll(REST_REQUESTOR_WAIT_SLEEP_TIME, TimeUnit.MILLISECONDS);
201 if (restRequest == null) {
202 // Poll timed out, check for request timeouts
203 timeoutExpiredRequests();
207 Properties inputExecutionProperties = restRequest.getExecutionProperties();
208 untaggedUrl = restConsumerProperties.getUrl();
209 if (inputExecutionProperties != null) {
210 Set<String> names = restConsumerProperties.getKeysFromUrl();
211 Set<String> inputProperty = inputExecutionProperties.stringPropertyNames();
213 names.stream().map(Optional::of)
214 .forEach(op -> op.filter(inputProperty::contains)
215 .orElseThrow(() -> new ApexEventRuntimeException(
216 "key\"" + op.get() + "\"specified on url \"" + restConsumerProperties.getUrl()
217 + "\"not found in execution properties passed by the current policy")));
219 untaggedUrl = names.stream().reduce(untaggedUrl,
220 (acc, str) -> acc.replace("{" + str + "}", (String) inputExecutionProperties.get(str)));
223 // Set the time stamp of the REST request
224 restRequest.setTimestamp(System.currentTimeMillis());
226 // Create a thread to process the REST request and place it on the map of ongoing
228 final RestRequestRunner restRequestRunner = new RestRequestRunner(restRequest);
229 ongoingRestRequestMap.put(restRequest, restRequestRunner);
231 // Start execution of the request
232 final Thread restRequestRunnerThread = new Thread(restRequestRunner);
233 restRequestRunnerThread.setName("RestRequestRunner_" + nextRequestRunnerThreadNo);
234 restRequestRunnerThread.start();
235 } catch (final InterruptedException e) {
236 LOGGER.debug("Thread interrupted, Reason {}", e.getMessage());
237 Thread.currentThread().interrupt();
245 * This method times out REST requests that have expired.
247 private void timeoutExpiredRequests() {
248 // Hold a list of timed out requests
249 final List<ApexRestRequest> timedoutRequestList = new ArrayList<>();
251 // Check for timeouts
252 for (final Entry<ApexRestRequest, RestRequestRunner> requestEntry : ongoingRestRequestMap.entrySet()) {
253 if (System.currentTimeMillis() - requestEntry.getKey().getTimestamp() > restRequestTimeout) {
254 requestEntry.getValue().stop();
255 timedoutRequestList.add(requestEntry.getKey());
259 // Interrupt timed out requests and remove them from the ongoing map
260 for (final ApexRestRequest timedoutRequest : timedoutRequestList) {
261 final String errorMessage =
262 "REST Requestor consumer (" + this.name + "), REST request timed out: " + timedoutRequest;
263 LOGGER.warn(errorMessage);
265 ongoingRestRequestMap.remove(timedoutRequest);
274 stopOrderedFlag = true;
276 while (consumerThread.isAlive()) {
277 ThreadUtilities.sleep(REST_REQUESTOR_WAIT_SLEEP_TIME);
282 * This class is used to start a thread for each request issued.
284 * @author Liam Fallon (liam.fallon@ericsson.com)
286 private class RestRequestRunner implements Runnable {
287 private static final String APPLICATION_JSON = "application/json";
289 // The REST request being processed by this thread
290 private final ApexRestRequest request;
292 // The thread executing the REST request
293 private Thread restRequestThread;
296 * Constructor, initialise the request runner with the request.
298 * @param request the request this runner will issue
300 private RestRequestRunner(final ApexRestRequest request) {
301 this.request = request;
309 // Get the thread for the request
310 restRequestThread = Thread.currentThread();
313 // Execute the REST request
314 final Response response = sendEventAsRestRequest(untaggedUrl);
316 // Match the return code
317 Matcher isPass = httpCodeFilterPattern.matcher(String.valueOf(response.getStatus()));
319 // Check that the request worked
320 if (!isPass.matches()) {
321 final String errorMessage = "reception of event from URL \"" + restConsumerProperties.getUrl()
322 + "\" failed with status code " + response.getStatus() + " and message \""
323 + response.readEntity(String.class) + "\"";
324 throw new ApexEventRuntimeException(errorMessage);
327 // Get the event we received
328 final String eventJsonString = response.readEntity(String.class);
330 // Check there is content
331 if (StringUtils.isBlank(eventJsonString)) {
332 final String errorMessage =
333 "received an empty response to \"" + request + "\" from URL \"" + untaggedUrl + "\"";
334 throw new ApexEventRuntimeException(errorMessage);
337 // build a key and value property in excutionProperties
338 Properties executionProperties = new Properties();
339 executionProperties.put(HTTP_CODE_STATUS, response.getStatus());
341 // Send the event into Apex
342 eventReceiver.receiveEvent(request.getExecutionId(), executionProperties, eventJsonString);
344 synchronized (eventsReceivedLock) {
347 } catch (final Exception e) {
348 LOGGER.warn("error receiving events on thread {}", consumerThread.getName(), e);
350 // Remove the request from the map of ongoing requests
351 ongoingRestRequestMap.remove(request);
356 * Stop the REST request.
358 private void stop() {
359 restRequestThread.interrupt();
363 * Execute the REST request.
366 * @return the response to the REST request
368 public Response sendEventAsRestRequest(String untaggedUrl) {
369 Builder headers = client.target(untaggedUrl).request(APPLICATION_JSON)
370 .headers(restConsumerProperties.getHttpHeadersAsMultivaluedMap());
371 switch (restConsumerProperties.getHttpMethod()) {
373 return headers.get();
376 return headers.put(Entity.json(request.getEvent()));
379 return headers.post(Entity.json(request.getEvent()));
382 return headers.delete();