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 javax.ws.rs.client.Client;
40 import javax.ws.rs.client.ClientBuilder;
41 import javax.ws.rs.client.Entity;
42 import javax.ws.rs.core.Response;
44 import org.onap.policy.apex.core.infrastructure.threading.ApplicationThreadFactory;
45 import org.onap.policy.apex.core.infrastructure.threading.ThreadUtilities;
46 import org.onap.policy.apex.service.engine.event.ApexEventConsumer;
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.PeeredReference;
51 import org.onap.policy.apex.service.parameters.eventhandler.EventHandlerParameters;
52 import org.onap.policy.apex.service.parameters.eventhandler.EventHandlerPeeredMode;
53 import org.slf4j.Logger;
54 import org.slf4j.LoggerFactory;
57 * This class implements an Apex event consumer that issues a REST request and returns the REST response to APEX as an
60 * @author Liam Fallon (liam.fallon@ericsson.com)
62 public class ApexRestRequestorConsumer implements ApexEventConsumer, Runnable {
63 // Get a reference to the logger
64 private static final Logger LOGGER = LoggerFactory.getLogger(ApexRestRequestorConsumer.class);
66 // The amount of time to wait in milliseconds between checks that the consumer thread has
68 private static final long REST_REQUESTOR_WAIT_SLEEP_TIME = 50;
70 // The REST parameters read from the parameter service
71 private RestRequestorCarrierTechnologyParameters restConsumerProperties;
73 // The timeout for REST requests
74 private long restRequestTimeout = RestRequestorCarrierTechnologyParameters.DEFAULT_REST_REQUEST_TIMEOUT;
76 // The event receiver that will receive events from this consumer
77 private ApexEventReceiver eventReceiver;
79 // The HTTP client that makes a REST call to get an input event for Apex
80 private Client client;
82 // The name for this consumer
83 private String name = null;
85 // The peer references for this event handler
86 private Map<EventHandlerPeeredMode, PeeredReference> peerReferenceMap = new EnumMap<>(EventHandlerPeeredMode.class);
88 // The consumer thread and stopping flag
89 private Thread consumerThread;
90 private boolean stopOrderedFlag = false;
92 // Temporary request holder for incoming REST requests
93 private final BlockingQueue<ApexRestRequest> incomingRestRequestQueue = new LinkedBlockingQueue<>();
95 // Map of ongoing REST request threads indexed by the time they started at
96 private final Map<ApexRestRequest, RestRequestRunner> ongoingRestRequestMap = new ConcurrentHashMap<>();
98 // The number of events received to date
99 private Object eventsReceivedLock = new Object();
100 private Integer eventsReceived = 0;
102 // The number of the next request runner thread
103 private static long nextRequestRunnerThreadNo = 0;
105 private String untaggedUrl = null;
108 public void init(final String consumerName, final EventHandlerParameters consumerParameters,
109 final ApexEventReceiver incomingEventReceiver) throws ApexEventException {
110 this.eventReceiver = incomingEventReceiver;
111 this.name = consumerName;
113 // Check and get the REST Properties
114 if (!(consumerParameters
115 .getCarrierTechnologyParameters() instanceof RestRequestorCarrierTechnologyParameters)) {
116 final String errorMessage = "specified consumer properties are not applicable to REST Requestor consumer ("
118 LOGGER.warn(errorMessage);
119 throw new ApexEventException(errorMessage);
121 restConsumerProperties = (RestRequestorCarrierTechnologyParameters) consumerParameters
122 .getCarrierTechnologyParameters();
124 // Check if we are in peered mode
125 if (!consumerParameters.isPeeredMode(EventHandlerPeeredMode.REQUESTOR)) {
126 final String errorMessage = "REST Requestor consumer (" + this.name
127 + ") must run in peered requestor mode with a REST Requestor producer";
128 LOGGER.warn(errorMessage);
129 throw new ApexEventException(errorMessage);
132 // Check if the HTTP method has been set
133 if (restConsumerProperties.getHttpMethod() == null) {
134 restConsumerProperties
135 .setHttpMethod(RestRequestorCarrierTechnologyParameters.DEFAULT_REQUESTOR_HTTP_METHOD);
138 // Check if the HTTP URL has been set
139 if (restConsumerProperties.getUrl() == null) {
140 final String errorMessage = "no URL has been specified on REST Requestor consumer (" + this.name + ")";
141 LOGGER.warn(errorMessage);
142 throw new ApexEventException(errorMessage);
145 // Check if the HTTP URL is valid
147 new URL(restConsumerProperties.getUrl());
148 } catch (final Exception e) {
149 final String errorMessage = "invalid URL has been specified on REST Requestor consumer (" + this.name + ")";
150 LOGGER.warn(errorMessage);
151 throw new ApexEventException(errorMessage, e);
154 // Set the requestor timeout
155 if (consumerParameters.getPeerTimeout(EventHandlerPeeredMode.REQUESTOR) != 0) {
156 restRequestTimeout = consumerParameters.getPeerTimeout(EventHandlerPeeredMode.REQUESTOR);
159 // Check if HTTP headers has been set
160 if (restConsumerProperties.checkHttpHeadersSet()) {
161 LOGGER.debug("REST Requestor consumer has http headers ({}): {}", this.name,
162 Arrays.deepToString(restConsumerProperties.getHttpHeaders()));
165 // Initialize the HTTP client
166 client = ClientBuilder.newClient();
170 * Receive an incoming REST request from the peered REST Requestor producer and queue it.
172 * @param restRequest the incoming rest request to queue
173 * @throws ApexEventRuntimeException on queueing errors
175 public void processRestRequest(final ApexRestRequest restRequest) {
176 // Push the event onto the queue for handling
178 incomingRestRequestQueue.add(restRequest);
179 } catch (final Exception requestException) {
180 final String errorMessage = "could not queue request \"" + restRequest + "\" on REST Requestor consumer ("
182 LOGGER.warn(errorMessage, requestException);
183 throw new ApexEventRuntimeException(errorMessage);
191 public void start() {
192 // Configure and start the event reception thread
193 final String threadName = this.getClass().getName() + ":" + this.name;
194 consumerThread = new ApplicationThreadFactory(threadName).newThread(this);
195 consumerThread.setDaemon(true);
196 consumerThread.start();
203 public String getName() {
208 * Get the number of events received to date.
210 * @return the number of events received
212 public int getEventsReceived() {
213 return eventsReceived;
220 public PeeredReference getPeeredReference(final EventHandlerPeeredMode peeredMode) {
221 return peerReferenceMap.get(peeredMode);
228 public void setPeeredReference(final EventHandlerPeeredMode peeredMode, final PeeredReference peeredReference) {
229 peerReferenceMap.put(peeredMode, peeredReference);
237 // The endless loop that receives events using REST calls
238 while (consumerThread.isAlive() && !stopOrderedFlag) {
240 // Take the next event from the queue
241 final ApexRestRequest restRequest = incomingRestRequestQueue.poll(REST_REQUESTOR_WAIT_SLEEP_TIME,
242 TimeUnit.MILLISECONDS);
243 if (restRequest == null) {
244 // Poll timed out, check for request timeouts
245 timeoutExpiredRequests();
249 Properties inputExecutionProperties = restRequest.getExecutionProperties();
250 untaggedUrl = restConsumerProperties.getUrl();
251 if (inputExecutionProperties != null) {
252 Set<String> names = restConsumerProperties.getKeysFromUrl();
253 Set<String> inputProperty = inputExecutionProperties.stringPropertyNames();
255 names.stream().map(Optional::of).forEach(op ->
256 op.filter(inputProperty::contains)
257 .orElseThrow(() -> new ApexEventRuntimeException(
258 "key\"" + op.get() + "\"specified on url \"" + restConsumerProperties.getUrl()
259 + "\"not found in execution properties passed by the current policy"))
262 untaggedUrl = names.stream().reduce(untaggedUrl,
263 (acc, str) -> acc.replace("{" + str + "}", (String) inputExecutionProperties.get(str)));
266 // Set the time stamp of the REST request
267 restRequest.setTimestamp(System.currentTimeMillis());
269 // Create a thread to process the REST request and place it on the map of ongoing
271 final RestRequestRunner restRequestRunner = new RestRequestRunner(restRequest);
272 ongoingRestRequestMap.put(restRequest, restRequestRunner);
274 // Start execution of the request
275 final Thread restRequestRunnerThread = new Thread(restRequestRunner);
276 restRequestRunnerThread.setName("RestRequestRunner_" + nextRequestRunnerThreadNo);
277 restRequestRunnerThread.start();
278 } catch (final InterruptedException e) {
279 LOGGER.debug("Thread interrupted, Reason {}", e.getMessage());
280 Thread.currentThread().interrupt();
288 * This method times out REST requests that have expired.
290 private void timeoutExpiredRequests() {
291 // Hold a list of timed out requests
292 final List<ApexRestRequest> timedoutRequestList = new ArrayList<>();
294 // Check for timeouts
295 for (final Entry<ApexRestRequest, RestRequestRunner> requestEntry : ongoingRestRequestMap.entrySet()) {
296 if (System.currentTimeMillis() - requestEntry.getKey().getTimestamp() > restRequestTimeout) {
297 requestEntry.getValue().stop();
298 timedoutRequestList.add(requestEntry.getKey());
302 // Interrupt timed out requests and remove them from the ongoing map
303 for (final ApexRestRequest timedoutRequest : timedoutRequestList) {
304 final String errorMessage = "REST Requestor consumer (" + this.name + "), REST request timed out: "
306 LOGGER.warn(errorMessage);
308 ongoingRestRequestMap.remove(timedoutRequest);
317 stopOrderedFlag = true;
319 while (consumerThread.isAlive()) {
320 ThreadUtilities.sleep(REST_REQUESTOR_WAIT_SLEEP_TIME);
325 * This class is used to start a thread for each request issued.
327 * @author Liam Fallon (liam.fallon@ericsson.com)
329 private class RestRequestRunner implements Runnable {
330 private static final String APPLICATION_JSON = "application/json";
332 // The REST request being processed by this thread
333 private final ApexRestRequest request;
335 // The thread executing the REST request
336 private Thread restRequestThread;
339 * Constructor, initialise the request runner with the request.
341 * @param request the request this runner will issue
343 private RestRequestRunner(final ApexRestRequest request) {
344 this.request = request;
352 // Get the thread for the request
353 restRequestThread = Thread.currentThread();
356 // Execute the REST request
357 final Response response = sendEventAsRestRequest(untaggedUrl);
359 // Check that the event request worked
360 if (!Response.Status.Family.familyOf(response.getStatus()).equals(Response.Status.Family.SUCCESSFUL)) {
361 final String errorMessage = "reception of response to \"" + request + "\" from URL \""
362 + untaggedUrl + "\" failed with status code "
363 + response.getStatus() + " and message \"" + response.readEntity(String.class)
365 throw new ApexEventRuntimeException(errorMessage);
368 // Get the event we received
369 final String eventJsonString = response.readEntity(String.class);
371 // Check there is content
372 if (eventJsonString == null || eventJsonString.trim().length() == 0) {
373 final String errorMessage = "received an enpty response to \"" + request + "\" from URL \""
374 + untaggedUrl + "\"";
375 throw new ApexEventRuntimeException(errorMessage);
378 // Send the event into Apex
379 eventReceiver.receiveEvent(request.getExecutionId(), new Properties(), eventJsonString);
381 synchronized (eventsReceivedLock) {
384 } catch (final Exception e) {
385 LOGGER.warn("error receiving events on thread {}", consumerThread.getName(), e);
387 // Remove the request from the map of ongoing requests
388 ongoingRestRequestMap.remove(request);
393 * Stop the REST request.
395 private void stop() {
396 restRequestThread.interrupt();
400 * Execute the REST request.
403 * @return the response to the REST request
405 public Response sendEventAsRestRequest(String untaggedUrl) {
406 switch (restConsumerProperties.getHttpMethod()) {
408 return client.target(untaggedUrl).request(APPLICATION_JSON)
409 .headers(restConsumerProperties.getHttpHeadersAsMultivaluedMap()).get();
412 return client.target(untaggedUrl).request(APPLICATION_JSON)
413 .headers(restConsumerProperties.getHttpHeadersAsMultivaluedMap())
414 .put(Entity.json(request.getEvent()));
417 return client.target(untaggedUrl).request(APPLICATION_JSON)
418 .headers(restConsumerProperties.getHttpHeadersAsMultivaluedMap())
419 .post(Entity.json(request.getEvent()));
422 return client.target(untaggedUrl).request(APPLICATION_JSON)
423 .headers(restConsumerProperties.getHttpHeadersAsMultivaluedMap()).delete();