2 * ============LICENSE_START=======================================================
3 * Copyright (C) 2016-2018 Ericsson. All rights reserved.
4 * Modifications Copyright (C) 2019 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.EnumMap;
28 import java.util.List;
30 import java.util.Map.Entry;
31 import java.util.Optional;
32 import java.util.Properties;
34 import java.util.concurrent.BlockingQueue;
35 import java.util.concurrent.ConcurrentHashMap;
36 import java.util.concurrent.LinkedBlockingQueue;
37 import java.util.concurrent.TimeUnit;
39 import java.util.regex.Matcher;
40 import java.util.regex.Pattern;
41 import javax.ws.rs.client.Client;
42 import javax.ws.rs.client.ClientBuilder;
43 import javax.ws.rs.client.Entity;
44 import javax.ws.rs.client.Invocation.Builder;
45 import javax.ws.rs.core.Response;
47 import org.apache.commons.lang3.StringUtils;
48 import org.onap.policy.apex.core.infrastructure.threading.ApplicationThreadFactory;
49 import org.onap.policy.apex.core.infrastructure.threading.ThreadUtilities;
50 import org.onap.policy.apex.service.engine.event.ApexEventConsumer;
51 import org.onap.policy.apex.service.engine.event.ApexEventException;
52 import org.onap.policy.apex.service.engine.event.ApexEventReceiver;
53 import org.onap.policy.apex.service.engine.event.ApexEventRuntimeException;
54 import org.onap.policy.apex.service.engine.event.PeeredReference;
55 import org.onap.policy.apex.service.parameters.eventhandler.EventHandlerParameters;
56 import org.onap.policy.apex.service.parameters.eventhandler.EventHandlerPeeredMode;
57 import org.slf4j.Logger;
58 import org.slf4j.LoggerFactory;
61 * This class implements an Apex event consumer that issues a REST request and returns the REST response to APEX as an
64 * @author Liam Fallon (liam.fallon@ericsson.com)
66 public class ApexRestRequestorConsumer implements ApexEventConsumer, Runnable {
67 // Get a reference to the logger
68 private static final Logger LOGGER = LoggerFactory.getLogger(ApexRestRequestorConsumer.class);
70 // The amount of time to wait in milliseconds between checks that the consumer thread has
72 private static final long REST_REQUESTOR_WAIT_SLEEP_TIME = 50;
74 // The Key for property
75 private static final String HTTP_CODE_STATUS = "HTTP_CODE_STATUS";
77 // The REST parameters read from the parameter service
78 private RestRequestorCarrierTechnologyParameters restConsumerProperties;
80 // The timeout for REST requests
81 private long restRequestTimeout = RestRequestorCarrierTechnologyParameters.DEFAULT_REST_REQUEST_TIMEOUT;
83 // The event receiver that will receive events from this consumer
84 private ApexEventReceiver eventReceiver;
86 // The HTTP client that makes a REST call to get an input event for Apex
87 private Client client;
89 // The name for this consumer
90 private String name = null;
92 // The peer references for this event handler
93 private Map<EventHandlerPeeredMode, PeeredReference> peerReferenceMap = new EnumMap<>(EventHandlerPeeredMode.class);
95 // The consumer thread and stopping flag
96 private Thread consumerThread;
97 private boolean stopOrderedFlag = false;
99 // Temporary request holder for incoming REST requests
100 private final BlockingQueue<ApexRestRequest> incomingRestRequestQueue = new LinkedBlockingQueue<>();
102 // Map of ongoing REST request threads indexed by the time they started at
103 private final Map<ApexRestRequest, RestRequestRunner> ongoingRestRequestMap = new ConcurrentHashMap<>();
105 // The number of events received to date
106 private Object eventsReceivedLock = new Object();
107 private Integer eventsReceived = 0;
109 // The number of the next request runner thread
110 private static long nextRequestRunnerThreadNo = 0;
112 private String untaggedUrl = null;
114 // The pattern for filtering status code
115 private Pattern httpCodeFilterPattern = null;
118 public void init(final String consumerName, final EventHandlerParameters consumerParameters,
119 final ApexEventReceiver incomingEventReceiver) throws ApexEventException {
120 this.eventReceiver = incomingEventReceiver;
121 this.name = consumerName;
123 // Check and get the REST Properties
124 if (!(consumerParameters
125 .getCarrierTechnologyParameters() instanceof RestRequestorCarrierTechnologyParameters)) {
126 final String errorMessage =
127 "specified consumer properties are not applicable to REST Requestor consumer (" + this.name + ")";
128 LOGGER.warn(errorMessage);
129 throw new ApexEventException(errorMessage);
131 restConsumerProperties =
132 (RestRequestorCarrierTechnologyParameters) consumerParameters.getCarrierTechnologyParameters();
134 // Check if we are in peered mode
135 if (!consumerParameters.isPeeredMode(EventHandlerPeeredMode.REQUESTOR)) {
136 final String errorMessage = "REST Requestor consumer (" + this.name
137 + ") must run in peered requestor mode with a REST Requestor producer";
138 LOGGER.warn(errorMessage);
139 throw new ApexEventException(errorMessage);
142 // Check if the HTTP method has been set
143 if (restConsumerProperties.getHttpMethod() == null) {
144 restConsumerProperties
145 .setHttpMethod(RestRequestorCarrierTechnologyParameters.DEFAULT_REQUESTOR_HTTP_METHOD);
148 // Check if the HTTP URL has been set
149 if (restConsumerProperties.getUrl() == null) {
150 final String errorMessage = "no URL has been specified on REST Requestor consumer (" + this.name + ")";
151 LOGGER.warn(errorMessage);
152 throw new ApexEventException(errorMessage);
155 // Check if the HTTP URL is valid
157 new URL(restConsumerProperties.getUrl());
158 } catch (final Exception e) {
159 final String errorMessage = "invalid URL has been specified on REST Requestor consumer (" + this.name + ")";
160 LOGGER.warn(errorMessage);
161 throw new ApexEventException(errorMessage, e);
164 this.httpCodeFilterPattern = Pattern.compile(restConsumerProperties.getHttpCodeFilter());
166 // Set the requestor timeout
167 if (consumerParameters.getPeerTimeout(EventHandlerPeeredMode.REQUESTOR) != 0) {
168 restRequestTimeout = consumerParameters.getPeerTimeout(EventHandlerPeeredMode.REQUESTOR);
171 // Check if HTTP headers has been set
172 if (restConsumerProperties.checkHttpHeadersSet()) {
173 LOGGER.debug("REST Requestor consumer has http headers ({}): {}", this.name,
174 Arrays.deepToString(restConsumerProperties.getHttpHeaders()));
177 // Initialize the HTTP client
178 client = ClientBuilder.newClient();
182 * Receive an incoming REST request from the peered REST Requestor producer and queue it.
184 * @param restRequest the incoming rest request to queue
185 * @throws ApexEventRuntimeException on queueing errors
187 public void processRestRequest(final ApexRestRequest restRequest) {
188 // Push the event onto the queue for handling
190 incomingRestRequestQueue.add(restRequest);
191 } catch (final Exception requestException) {
192 final String errorMessage =
193 "could not queue request \"" + restRequest + "\" on REST Requestor consumer (" + this.name + ")";
194 LOGGER.warn(errorMessage, requestException);
195 throw new ApexEventRuntimeException(errorMessage);
203 public void start() {
204 // Configure and start the event reception thread
205 final String threadName = this.getClass().getName() + ":" + this.name;
206 consumerThread = new ApplicationThreadFactory(threadName).newThread(this);
207 consumerThread.setDaemon(true);
208 consumerThread.start();
215 public String getName() {
220 * Get the number of events received to date.
222 * @return the number of events received
224 public int getEventsReceived() {
225 return eventsReceived;
232 public PeeredReference getPeeredReference(final EventHandlerPeeredMode peeredMode) {
233 return peerReferenceMap.get(peeredMode);
240 public void setPeeredReference(final EventHandlerPeeredMode peeredMode, final PeeredReference peeredReference) {
241 peerReferenceMap.put(peeredMode, peeredReference);
249 // The endless loop that receives events using REST calls
250 while (consumerThread.isAlive() && !stopOrderedFlag) {
252 // Take the next event from the queue
253 final ApexRestRequest restRequest =
254 incomingRestRequestQueue.poll(REST_REQUESTOR_WAIT_SLEEP_TIME, TimeUnit.MILLISECONDS);
255 if (restRequest == null) {
256 // Poll timed out, check for request timeouts
257 timeoutExpiredRequests();
261 Properties inputExecutionProperties = restRequest.getExecutionProperties();
262 untaggedUrl = restConsumerProperties.getUrl();
263 if (inputExecutionProperties != null) {
264 Set<String> names = restConsumerProperties.getKeysFromUrl();
265 Set<String> inputProperty = inputExecutionProperties.stringPropertyNames();
267 names.stream().map(Optional::of).forEach(op ->
268 op.filter(inputProperty::contains)
269 .orElseThrow(() -> new ApexEventRuntimeException(
270 "key\"" + op.get() + "\"specified on url \"" + restConsumerProperties.getUrl()
271 + "\"not found in execution properties passed by the current policy")));
273 untaggedUrl = names.stream().reduce(untaggedUrl,
274 (acc, str) -> acc.replace("{" + str + "}", (String) inputExecutionProperties.get(str)));
277 // Set the time stamp of the REST request
278 restRequest.setTimestamp(System.currentTimeMillis());
280 // Create a thread to process the REST request and place it on the map of ongoing
282 final RestRequestRunner restRequestRunner = new RestRequestRunner(restRequest);
283 ongoingRestRequestMap.put(restRequest, restRequestRunner);
285 // Start execution of the request
286 final Thread restRequestRunnerThread = new Thread(restRequestRunner);
287 restRequestRunnerThread.setName("RestRequestRunner_" + nextRequestRunnerThreadNo);
288 restRequestRunnerThread.start();
289 } catch (final InterruptedException e) {
290 LOGGER.debug("Thread interrupted, Reason {}", e.getMessage());
291 Thread.currentThread().interrupt();
299 * This method times out REST requests that have expired.
301 private void timeoutExpiredRequests() {
302 // Hold a list of timed out requests
303 final List<ApexRestRequest> timedoutRequestList = new ArrayList<>();
305 // Check for timeouts
306 for (final Entry<ApexRestRequest, RestRequestRunner> requestEntry : ongoingRestRequestMap.entrySet()) {
307 if (System.currentTimeMillis() - requestEntry.getKey().getTimestamp() > restRequestTimeout) {
308 requestEntry.getValue().stop();
309 timedoutRequestList.add(requestEntry.getKey());
313 // Interrupt timed out requests and remove them from the ongoing map
314 for (final ApexRestRequest timedoutRequest : timedoutRequestList) {
315 final String errorMessage =
316 "REST Requestor consumer (" + this.name + "), REST request timed out: " + timedoutRequest;
317 LOGGER.warn(errorMessage);
319 ongoingRestRequestMap.remove(timedoutRequest);
328 stopOrderedFlag = true;
330 while (consumerThread.isAlive()) {
331 ThreadUtilities.sleep(REST_REQUESTOR_WAIT_SLEEP_TIME);
336 * This class is used to start a thread for each request issued.
338 * @author Liam Fallon (liam.fallon@ericsson.com)
340 private class RestRequestRunner implements Runnable {
341 private static final String APPLICATION_JSON = "application/json";
343 // The REST request being processed by this thread
344 private final ApexRestRequest request;
346 // The thread executing the REST request
347 private Thread restRequestThread;
350 * Constructor, initialise the request runner with the request.
352 * @param request the request this runner will issue
354 private RestRequestRunner(final ApexRestRequest request) {
355 this.request = request;
363 // Get the thread for the request
364 restRequestThread = Thread.currentThread();
367 // Execute the REST request
368 final Response response = sendEventAsRestRequest(untaggedUrl);
370 // Match the return code
371 Matcher isPass = httpCodeFilterPattern.matcher(String.valueOf(response.getStatus()));
373 // Check that the request worked
374 if (!isPass.matches()) {
375 final String errorMessage ="reception of event from URL \"" + restConsumerProperties.getUrl()
376 + "\" failed with status code " + response.getStatus() + " and message \""
377 + response.readEntity(String.class) + "\"";
378 throw new ApexEventRuntimeException(errorMessage);
381 // Get the event we received
382 final String eventJsonString = response.readEntity(String.class);
384 // Check there is content
385 if (StringUtils.isBlank(eventJsonString)) {
386 final String errorMessage =
387 "received an empty response to \"" + request + "\" from URL \"" + untaggedUrl + "\"";
388 throw new ApexEventRuntimeException(errorMessage);
391 // build a key and value property in excutionProperties
392 Properties executionProperties = new Properties();
393 executionProperties.put(HTTP_CODE_STATUS, response.getStatus());
395 // Send the event into Apex
396 eventReceiver.receiveEvent(request.getExecutionId(), executionProperties, eventJsonString);
398 synchronized (eventsReceivedLock) {
401 } catch (final Exception e) {
402 LOGGER.warn("error receiving events on thread {}", consumerThread.getName(), e);
404 // Remove the request from the map of ongoing requests
405 ongoingRestRequestMap.remove(request);
410 * Stop the REST request.
412 private void stop() {
413 restRequestThread.interrupt();
417 * Execute the REST request.
420 * @return the response to the REST request
422 public Response sendEventAsRestRequest(String untaggedUrl) {
423 Builder headers = client.target(untaggedUrl).request(APPLICATION_JSON)
424 .headers(restConsumerProperties.getHttpHeadersAsMultivaluedMap());
425 switch (restConsumerProperties.getHttpMethod()) {
427 return headers.get();
430 return headers.put(Entity.json(request.getEvent()));
433 return headers.post(Entity.json(request.getEvent()));
436 return headers.delete();