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
12 * http://www.apache.org/licenses/LICENSE-2.0
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.
20 * SPDX-License-Identifier: Apache-2.0
21 * ============LICENSE_END=========================================================
24 package org.onap.policy.apex.plugins.event.carrier.restrequestor;
27 import java.util.ArrayList;
28 import java.util.Arrays;
29 import java.util.List;
31 import java.util.Map.Entry;
32 import java.util.Optional;
33 import java.util.Properties;
35 import java.util.concurrent.BlockingQueue;
36 import java.util.concurrent.ConcurrentHashMap;
37 import java.util.concurrent.LinkedBlockingQueue;
38 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.ThreadUtilities;
49 import org.onap.policy.apex.service.engine.event.ApexEventException;
50 import org.onap.policy.apex.service.engine.event.ApexEventReceiver;
51 import org.onap.policy.apex.service.engine.event.ApexEventRuntimeException;
52 import org.onap.policy.apex.service.engine.event.ApexPluginsEventConsumer;
53 import org.onap.policy.apex.service.parameters.carriertechnology.RestPluginCarrierTechnologyParameters.HttpMethod;
54 import org.onap.policy.apex.service.parameters.eventhandler.EventHandlerParameters;
55 import org.onap.policy.apex.service.parameters.eventhandler.EventHandlerPeeredMode;
56 import org.onap.policy.common.endpoints.event.comm.Topic.CommInfrastructure;
57 import org.onap.policy.common.endpoints.utils.NetLoggerUtil;
58 import org.onap.policy.common.endpoints.utils.NetLoggerUtil.EventType;
59 import org.slf4j.Logger;
60 import org.slf4j.LoggerFactory;
63 * This class implements an Apex event consumer that issues a REST request and returns the REST response to APEX as an
66 * @author Liam Fallon (liam.fallon@ericsson.com)
68 public class ApexRestRequestorConsumer extends ApexPluginsEventConsumer {
69 // Get a reference to the logger
70 private static final Logger LOGGER = LoggerFactory.getLogger(ApexRestRequestorConsumer.class);
72 // The amount of time to wait in milliseconds between checks that the consumer thread has
74 private static final long REST_REQUESTOR_WAIT_SLEEP_TIME = 50;
76 // The REST parameters read from the parameter service
77 private RestRequestorCarrierTechnologyParameters restConsumerProperties;
79 // The timeout for REST requests
80 private long restRequestTimeout = RestRequestorCarrierTechnologyParameters.DEFAULT_REST_REQUEST_TIMEOUT;
82 // The event receiver that will receive events from this consumer
83 private ApexEventReceiver eventReceiver;
85 // The HTTP client that makes a REST call to get an input event for Apex
86 private Client client;
88 // Temporary request holder for incoming REST requests
89 private final BlockingQueue<ApexRestRequest> incomingRestRequestQueue = new LinkedBlockingQueue<>();
91 // Map of ongoing REST request threads indexed by the time they started at
92 private final Map<ApexRestRequest, RestRequestRunner> ongoingRestRequestMap = new ConcurrentHashMap<>();
94 // The number of events received to date
95 private Object eventsReceivedLock = new Object();
97 private int eventsReceived = 0;
99 // The number of the next request runner thread
100 private static long nextRequestRunnerThreadNo = 0;
102 // The pattern for filtering status code
103 private Pattern httpCodeFilterPattern = null;
106 public void init(final String consumerName, final EventHandlerParameters consumerParameters,
107 final ApexEventReceiver incomingEventReceiver) throws ApexEventException {
108 this.eventReceiver = incomingEventReceiver;
109 this.name = consumerName;
111 // Check and get the REST Properties
112 if (!(consumerParameters
113 .getCarrierTechnologyParameters() instanceof RestRequestorCarrierTechnologyParameters)) {
114 final String errorMessage =
115 "specified consumer properties are not applicable to REST Requestor consumer (" + this.name + ")";
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 throw new ApexEventException(errorMessage);
128 // Check if the HTTP method has been set
129 if (restConsumerProperties.getHttpMethod() == null) {
130 restConsumerProperties
131 .setHttpMethod(RestRequestorCarrierTechnologyParameters.DEFAULT_REQUESTOR_HTTP_METHOD);
134 // Check if the HTTP URL has been set
135 if (restConsumerProperties.getUrl() == null) {
136 final String errorMessage = "no URL has been specified on REST Requestor consumer (" + this.name + ")";
137 throw new ApexEventException(errorMessage);
140 // Check if the HTTP URL is valid
142 new URL(restConsumerProperties.getUrl());
143 } catch (final Exception e) {
144 final String errorMessage = "invalid URL has been specified on REST Requestor consumer (" + this.name + ")";
145 throw new ApexEventException(errorMessage, e);
148 this.httpCodeFilterPattern = Pattern.compile(restConsumerProperties.getHttpCodeFilter());
150 // Set the requestor timeout
151 if (consumerParameters.getPeerTimeout(EventHandlerPeeredMode.REQUESTOR) != 0) {
152 restRequestTimeout = consumerParameters.getPeerTimeout(EventHandlerPeeredMode.REQUESTOR);
155 // Check if HTTP headers has been set
156 if (restConsumerProperties.checkHttpHeadersSet()) {
157 final String httpHeaderString = Arrays.deepToString(restConsumerProperties.getHttpHeaders());
158 LOGGER.debug("REST Requestor consumer has http headers ({}): {}", this.name, httpHeaderString);
161 // Initialize the HTTP client
162 client = ClientBuilder.newClient();
166 * Receive an incoming REST request from the peered REST Requestor producer and queue it.
168 * @param restRequest the incoming rest request to queue
169 * @throws ApexEventRuntimeException on queueing errors
171 public void processRestRequest(final ApexRestRequest restRequest) {
172 // Push the event onto the queue for handling
174 incomingRestRequestQueue.add(restRequest);
175 } catch (final Exception requestException) {
176 final String errorMessage =
177 "could not queue request \"" + restRequest + "\" on REST Requestor consumer (" + this.name + ")";
178 throw new ApexEventRuntimeException(errorMessage);
187 // The endless loop that receives events using REST calls
188 while (consumerThread.isAlive() && !stopOrderedFlag) {
190 // Take the next event from the queue
191 final ApexRestRequest restRequest =
192 incomingRestRequestQueue.poll(REST_REQUESTOR_WAIT_SLEEP_TIME, TimeUnit.MILLISECONDS);
193 if (restRequest == null) {
194 // Poll timed out, check for request timeouts
195 timeoutExpiredRequests();
199 // Set the time stamp of the REST request
200 restRequest.setTimestamp(System.currentTimeMillis());
202 // Create a thread to process the REST request and place it on the map of ongoing
204 final RestRequestRunner restRequestRunner = new RestRequestRunner(restRequest);
205 ongoingRestRequestMap.put(restRequest, restRequestRunner);
207 // Start execution of the request
208 final Thread restRequestRunnerThread = new Thread(restRequestRunner);
209 restRequestRunnerThread.setName("RestRequestRunner_" + nextRequestRunnerThreadNo);
210 restRequestRunnerThread.start();
211 } catch (final InterruptedException e) {
212 LOGGER.debug("Thread interrupted, Reason {}", e.getMessage());
213 Thread.currentThread().interrupt();
221 * This method times out REST requests that have expired.
223 private void timeoutExpiredRequests() {
224 // Hold a list of timed out requests
225 final List<ApexRestRequest> timedoutRequestList = new ArrayList<>();
227 // Check for timeouts
228 for (final Entry<ApexRestRequest, RestRequestRunner> requestEntry : ongoingRestRequestMap.entrySet()) {
229 if (System.currentTimeMillis() - requestEntry.getKey().getTimestamp() > restRequestTimeout) {
230 requestEntry.getValue().stop();
231 timedoutRequestList.add(requestEntry.getKey());
235 // Interrupt timed out requests and remove them from the ongoing map
236 for (final ApexRestRequest timedoutRequest : timedoutRequestList) {
237 final String errorMessage =
238 "REST Requestor consumer (" + this.name + "), REST request timed out: " + timedoutRequest;
239 LOGGER.warn(errorMessage);
241 ongoingRestRequestMap.remove(timedoutRequest);
250 stopOrderedFlag = true;
252 while (consumerThread.isAlive()) {
253 ThreadUtilities.sleep(REST_REQUESTOR_WAIT_SLEEP_TIME);
258 * This class is used to start a thread for each request issued.
260 * @author Liam Fallon (liam.fallon@ericsson.com)
262 private class RestRequestRunner implements Runnable {
263 private static final String APPLICATION_JSON = "application/json";
265 // The REST request being processed by this thread
266 private final ApexRestRequest request;
268 // The thread executing the REST request
269 private Thread restRequestThread;
272 * Constructor, initialise the request runner with the request.
274 * @param request the request this runner will issue
276 private RestRequestRunner(final ApexRestRequest request) {
277 this.request = request;
285 // Get the thread for the request
286 restRequestThread = Thread.currentThread();
287 Properties inputExecutionProperties = request.getExecutionProperties();
288 String url = restConsumerProperties.getUrl();
289 Set<String> names = restConsumerProperties.getKeysFromUrl();
290 if (!names.isEmpty() && inputExecutionProperties != null) {
291 Set<String> inputProperty = inputExecutionProperties.stringPropertyNames();
293 names.stream().map(Optional::of)
294 .forEach(op -> op.filter(inputProperty::contains)
295 .orElseThrow(() -> new ApexEventRuntimeException(
296 "key\"" + op.get() + "\"specified on url \"" + restConsumerProperties.getUrl()
297 + "\"not found in execution properties passed by the current policy")));
299 url = names.stream().reduce(url,
300 (acc, str) -> acc.replace("{" + str + "}", (String) inputExecutionProperties.get(str)));
303 if (restConsumerProperties.getHttpMethod().equals(HttpMethod.PUT)
304 || restConsumerProperties.getHttpMethod().equals(HttpMethod.POST)) {
305 NetLoggerUtil.log(EventType.OUT, CommInfrastructure.REST, url, request.getEvent().toString());
307 // Execute the REST request
308 final Response response = sendEventAsRestRequest(url);
309 // Get the event we received
310 final String eventJsonString = response.readEntity(String.class);
311 NetLoggerUtil.log(EventType.IN, CommInfrastructure.REST, url, eventJsonString);
312 // Match the return code
313 Matcher isPass = httpCodeFilterPattern.matcher(String.valueOf(response.getStatus()));
315 // Check that the request worked
316 if (!isPass.matches()) {
317 final String errorMessage = "reception of event from URL \"" + restConsumerProperties.getUrl()
318 + "\" failed with status code " + response.getStatus();
319 throw new ApexEventRuntimeException(errorMessage);
322 // Check there is content
323 if (StringUtils.isBlank(eventJsonString)) {
324 final String errorMessage =
325 "received an empty response to \"" + request + "\" from URL \"" + url + "\"";
326 throw new ApexEventRuntimeException(errorMessage);
329 // Send the event into Apex
330 eventReceiver.receiveEvent(request.getExecutionId(), inputExecutionProperties, eventJsonString);
332 synchronized (eventsReceivedLock) {
335 } catch (final Exception e) {
336 LOGGER.warn("error receiving events on thread {}", consumerThread.getName(), e);
338 // Remove the request from the map of ongoing requests
339 ongoingRestRequestMap.remove(request);
344 * Stop the REST request.
346 private void stop() {
347 restRequestThread.interrupt();
351 * Execute the REST request.
354 * @return the response to the REST request
356 public Response sendEventAsRestRequest(String url) {
357 Builder headers = client.target(url).request(APPLICATION_JSON)
358 .headers(restConsumerProperties.getHttpHeadersAsMultivaluedMap());
359 switch (restConsumerProperties.getHttpMethod()) {
361 return headers.get();
364 return headers.put(Entity.json(request.getEvent()));
367 return headers.post(Entity.json(request.getEvent()));
370 return headers.delete();