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;
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;
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 LOGGER.warn(errorMessage);
116 throw new ApexEventException(errorMessage);
118 restConsumerProperties =
119 (RestRequestorCarrierTechnologyParameters) consumerParameters.getCarrierTechnologyParameters();
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 LOGGER.warn(errorMessage);
126 throw new ApexEventException(errorMessage);
129 // Check if the HTTP method has been set
130 if (restConsumerProperties.getHttpMethod() == null) {
131 restConsumerProperties
132 .setHttpMethod(RestRequestorCarrierTechnologyParameters.DEFAULT_REQUESTOR_HTTP_METHOD);
135 // Check if the HTTP URL has been set
136 if (restConsumerProperties.getUrl() == null) {
137 final String errorMessage = "no URL has been specified on REST Requestor consumer (" + this.name + ")";
138 LOGGER.warn(errorMessage);
139 throw new ApexEventException(errorMessage);
142 // Check if the HTTP URL is valid
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 LOGGER.warn(errorMessage);
148 throw new ApexEventException(errorMessage, e);
151 this.httpCodeFilterPattern = Pattern.compile(restConsumerProperties.getHttpCodeFilter());
153 // Set the requestor timeout
154 if (consumerParameters.getPeerTimeout(EventHandlerPeeredMode.REQUESTOR) != 0) {
155 restRequestTimeout = consumerParameters.getPeerTimeout(EventHandlerPeeredMode.REQUESTOR);
158 // Check if HTTP headers has been set
159 if (restConsumerProperties.checkHttpHeadersSet()) {
160 LOGGER.debug("REST Requestor consumer has http headers ({}): {}", this.name,
161 Arrays.deepToString(restConsumerProperties.getHttpHeaders()));
164 // Initialize the HTTP client
165 client = ClientBuilder.newClient();
169 * Receive an incoming REST request from the peered REST Requestor producer and queue it.
171 * @param restRequest the incoming rest request to queue
172 * @throws ApexEventRuntimeException on queueing errors
174 public void processRestRequest(final ApexRestRequest restRequest) {
175 // Push the event onto the queue for handling
177 incomingRestRequestQueue.add(restRequest);
178 } catch (final Exception requestException) {
179 final String errorMessage =
180 "could not queue request \"" + restRequest + "\" on REST Requestor consumer (" + this.name + ")";
181 LOGGER.warn(errorMessage, requestException);
182 throw new ApexEventRuntimeException(errorMessage);
187 * Get the number of events received to date.
189 * @return the number of events received
191 public int getEventsReceived() {
192 return eventsReceived;
200 // The endless loop that receives events using REST calls
201 while (consumerThread.isAlive() && !stopOrderedFlag) {
203 // Take the next event from the queue
204 final ApexRestRequest restRequest =
205 incomingRestRequestQueue.poll(REST_REQUESTOR_WAIT_SLEEP_TIME, TimeUnit.MILLISECONDS);
206 if (restRequest == null) {
207 // Poll timed out, check for request timeouts
208 timeoutExpiredRequests();
212 Properties inputExecutionProperties = restRequest.getExecutionProperties();
213 untaggedUrl = restConsumerProperties.getUrl();
214 if (inputExecutionProperties != null) {
215 Set<String> names = restConsumerProperties.getKeysFromUrl();
216 Set<String> inputProperty = inputExecutionProperties.stringPropertyNames();
218 names.stream().map(Optional::of).forEach(op ->
219 op.filter(inputProperty::contains)
220 .orElseThrow(() -> new ApexEventRuntimeException(
221 "key\"" + op.get() + "\"specified on url \"" + restConsumerProperties.getUrl()
222 + "\"not found in execution properties passed by the current policy")));
224 untaggedUrl = names.stream().reduce(untaggedUrl,
225 (acc, str) -> acc.replace("{" + str + "}", (String) inputExecutionProperties.get(str)));
228 // Set the time stamp of the REST request
229 restRequest.setTimestamp(System.currentTimeMillis());
231 // Create a thread to process the REST request and place it on the map of ongoing
233 final RestRequestRunner restRequestRunner = new RestRequestRunner(restRequest);
234 ongoingRestRequestMap.put(restRequest, restRequestRunner);
236 // Start execution of the request
237 final Thread restRequestRunnerThread = new Thread(restRequestRunner);
238 restRequestRunnerThread.setName("RestRequestRunner_" + nextRequestRunnerThreadNo);
239 restRequestRunnerThread.start();
240 } catch (final InterruptedException e) {
241 LOGGER.debug("Thread interrupted, Reason {}", e.getMessage());
242 Thread.currentThread().interrupt();
250 * This method times out REST requests that have expired.
252 private void timeoutExpiredRequests() {
253 // Hold a list of timed out requests
254 final List<ApexRestRequest> timedoutRequestList = new ArrayList<>();
256 // Check for timeouts
257 for (final Entry<ApexRestRequest, RestRequestRunner> requestEntry : ongoingRestRequestMap.entrySet()) {
258 if (System.currentTimeMillis() - requestEntry.getKey().getTimestamp() > restRequestTimeout) {
259 requestEntry.getValue().stop();
260 timedoutRequestList.add(requestEntry.getKey());
264 // Interrupt timed out requests and remove them from the ongoing map
265 for (final ApexRestRequest timedoutRequest : timedoutRequestList) {
266 final String errorMessage =
267 "REST Requestor consumer (" + this.name + "), REST request timed out: " + timedoutRequest;
268 LOGGER.warn(errorMessage);
270 ongoingRestRequestMap.remove(timedoutRequest);
279 stopOrderedFlag = true;
281 while (consumerThread.isAlive()) {
282 ThreadUtilities.sleep(REST_REQUESTOR_WAIT_SLEEP_TIME);
287 * This class is used to start a thread for each request issued.
289 * @author Liam Fallon (liam.fallon@ericsson.com)
291 private class RestRequestRunner implements Runnable {
292 private static final String APPLICATION_JSON = "application/json";
294 // The REST request being processed by this thread
295 private final ApexRestRequest request;
297 // The thread executing the REST request
298 private Thread restRequestThread;
301 * Constructor, initialise the request runner with the request.
303 * @param request the request this runner will issue
305 private RestRequestRunner(final ApexRestRequest request) {
306 this.request = request;
314 // Get the thread for the request
315 restRequestThread = Thread.currentThread();
318 // Execute the REST request
319 final Response response = sendEventAsRestRequest(untaggedUrl);
321 // Match the return code
322 Matcher isPass = httpCodeFilterPattern.matcher(String.valueOf(response.getStatus()));
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() + " and message \""
328 + response.readEntity(String.class) + "\"";
329 throw new ApexEventRuntimeException(errorMessage);
332 // Get the event we received
333 final String eventJsonString = response.readEntity(String.class);
335 // Check there is content
336 if (StringUtils.isBlank(eventJsonString)) {
337 final String errorMessage =
338 "received an empty response to \"" + request + "\" from URL \"" + untaggedUrl + "\"";
339 throw new ApexEventRuntimeException(errorMessage);
342 // build a key and value property in excutionProperties
343 Properties executionProperties = new Properties();
344 executionProperties.put(HTTP_CODE_STATUS, response.getStatus());
346 // Send the event into Apex
347 eventReceiver.receiveEvent(request.getExecutionId(), executionProperties, eventJsonString);
349 synchronized (eventsReceivedLock) {
352 } catch (final Exception e) {
353 LOGGER.warn("error receiving events on thread {}", consumerThread.getName(), e);
355 // Remove the request from the map of ongoing requests
356 ongoingRestRequestMap.remove(request);
361 * Stop the REST request.
363 private void stop() {
364 restRequestThread.interrupt();
368 * Execute the REST request.
371 * @return the response to the REST request
373 public Response sendEventAsRestRequest(String untaggedUrl) {
374 Builder headers = client.target(untaggedUrl).request(APPLICATION_JSON)
375 .headers(restConsumerProperties.getHttpHeadersAsMultivaluedMap());
376 switch (restConsumerProperties.getHttpMethod()) {
378 return headers.get();
381 return headers.put(Entity.json(request.getEvent()));
384 return headers.post(Entity.json(request.getEvent()));
387 return headers.delete();