2 * ============LICENSE_START=======================================================
3 * Copyright (C) 2016-2018 Ericsson. All rights reserved.
4 * Modifications Copyright (C) 2019-2020, 2023-2024 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;
26 import jakarta.ws.rs.client.Client;
27 import jakarta.ws.rs.client.ClientBuilder;
28 import jakarta.ws.rs.client.Entity;
29 import jakarta.ws.rs.client.Invocation.Builder;
30 import jakarta.ws.rs.core.Response;
32 import java.util.ArrayList;
33 import java.util.Arrays;
34 import java.util.List;
36 import java.util.Map.Entry;
37 import java.util.Optional;
39 import java.util.concurrent.BlockingQueue;
40 import java.util.concurrent.ConcurrentHashMap;
41 import java.util.concurrent.LinkedBlockingQueue;
42 import java.util.concurrent.TimeUnit;
43 import java.util.regex.Pattern;
45 import org.apache.commons.lang3.StringUtils;
46 import org.onap.policy.apex.core.infrastructure.threading.ThreadUtilities;
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.ApexPluginsEventConsumer;
51 import org.onap.policy.apex.service.parameters.carriertechnology.RestPluginCarrierTechnologyParameters.HttpMethod;
52 import org.onap.policy.apex.service.parameters.eventhandler.EventHandlerParameters;
53 import org.onap.policy.apex.service.parameters.eventhandler.EventHandlerPeeredMode;
54 import org.onap.policy.common.endpoints.event.comm.Topic.CommInfrastructure;
55 import org.onap.policy.common.endpoints.utils.NetLoggerUtil;
56 import org.onap.policy.common.endpoints.utils.NetLoggerUtil.EventType;
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 extends ApexPluginsEventConsumer {
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 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 final Object eventsReceivedLock = new Object();
95 private int eventsReceived = 0;
97 // The number of the next request runner thread
98 private static long nextRequestRunnerThreadNo = 0;
100 // The pattern for filtering status code
101 private Pattern httpCodeFilterPattern = null;
104 public void init(final String consumerName, final EventHandlerParameters consumerParameters,
105 final ApexEventReceiver incomingEventReceiver) throws ApexEventException {
106 this.eventReceiver = incomingEventReceiver;
107 this.name = consumerName;
109 // Check and get the REST Properties
110 if (!(consumerParameters
111 .getCarrierTechnologyParameters() instanceof RestRequestorCarrierTechnologyParameters)) {
112 final String errorMessage =
113 "specified consumer properties are not applicable to REST Requestor consumer (" + this.name + ")";
114 throw new ApexEventException(errorMessage);
116 restConsumerProperties =
117 (RestRequestorCarrierTechnologyParameters) consumerParameters.getCarrierTechnologyParameters();
119 // Check if we are in peered mode
120 if (!consumerParameters.isPeeredMode(EventHandlerPeeredMode.REQUESTOR)) {
121 final String errorMessage = "REST Requestor consumer (" + this.name
122 + ") must run in peered requestor mode with a REST Requestor producer";
123 throw new ApexEventException(errorMessage);
126 // Check if the HTTP method has been set
127 if (restConsumerProperties.getHttpMethod() == null) {
128 restConsumerProperties
129 .setHttpMethod(RestRequestorCarrierTechnologyParameters.DEFAULT_REQUESTOR_HTTP_METHOD);
132 // Check if the HTTP URL has been set
133 if (restConsumerProperties.getUrl() == null) {
134 final String errorMessage = "no URL has been specified on REST Requestor consumer (" + this.name + ")";
135 throw new ApexEventException(errorMessage);
138 // Check if the HTTP URL is valid
140 new URL(restConsumerProperties.getUrl());
141 } catch (final Exception e) {
142 final String errorMessage = "invalid URL has been specified on REST Requestor consumer (" + this.name + ")";
143 throw new ApexEventException(errorMessage, e);
146 this.httpCodeFilterPattern = Pattern.compile(restConsumerProperties.getHttpCodeFilter());
148 // Set the requestor timeout
149 if (consumerParameters.getPeerTimeout(EventHandlerPeeredMode.REQUESTOR) != 0) {
150 restRequestTimeout = consumerParameters.getPeerTimeout(EventHandlerPeeredMode.REQUESTOR);
153 // Check if HTTP headers has been set
154 if (restConsumerProperties.checkHttpHeadersSet()) {
155 final var httpHeaderString = Arrays.deepToString(restConsumerProperties.getHttpHeaders());
156 LOGGER.debug("REST Requestor consumer has http headers ({}): {}", this.name, httpHeaderString);
159 // Initialize the HTTP client
160 client = ClientBuilder.newClient();
164 * Receive an incoming REST request from the peered REST Requestor producer and queue it.
166 * @param restRequest the incoming rest request to queue
167 * @throws ApexEventRuntimeException on queueing errors
169 public void processRestRequest(final ApexRestRequest restRequest) {
170 // Push the event onto the queue for handling
172 incomingRestRequestQueue.add(restRequest);
173 } catch (final Exception requestException) {
174 final String errorMessage =
175 "could not queue request \"" + restRequest + "\" on REST Requestor consumer (" + this.name + ")";
176 throw new ApexEventRuntimeException(errorMessage);
185 // The endless loop that receives events using REST calls
186 while (consumerThread.isAlive() && !stopOrderedFlag) {
188 // Take the next event from the queue
189 final ApexRestRequest restRequest =
190 incomingRestRequestQueue.poll(REST_REQUESTOR_WAIT_SLEEP_TIME, TimeUnit.MILLISECONDS);
191 if (restRequest == null) {
192 // Poll timed out, check for request timeouts
193 timeoutExpiredRequests();
197 // Set the time stamp of the REST request
198 restRequest.setTimestamp(System.currentTimeMillis());
200 // Create a thread to process the REST request and place it on the map of ongoing
202 final var restRequestRunner = new RestRequestRunner(restRequest);
203 ongoingRestRequestMap.put(restRequest, restRequestRunner);
205 // Start execution of the request
206 final var restRequestRunnerThread = new Thread(restRequestRunner);
207 restRequestRunnerThread.setName("RestRequestRunner_" + nextRequestRunnerThreadNo);
208 restRequestRunnerThread.start();
209 } catch (final InterruptedException e) {
210 LOGGER.debug("Thread interrupted, Reason {}", e.getMessage());
211 Thread.currentThread().interrupt();
219 * This method times out REST requests that have expired.
221 private void timeoutExpiredRequests() {
222 // Hold a list of timed out requests
223 final List<ApexRestRequest> timedoutRequestList = new ArrayList<>();
225 // Check for timeouts
226 for (final Entry<ApexRestRequest, RestRequestRunner> requestEntry : ongoingRestRequestMap.entrySet()) {
227 if (System.currentTimeMillis() - requestEntry.getKey().getTimestamp() > restRequestTimeout) {
228 requestEntry.getValue().stop();
229 timedoutRequestList.add(requestEntry.getKey());
233 // Interrupt timed out requests and remove them from the ongoing map
234 for (final ApexRestRequest timedoutRequest : timedoutRequestList) {
235 final String errorMessage =
236 "REST Requestor consumer (" + this.name + "), REST request timed out: " + timedoutRequest;
237 LOGGER.warn(errorMessage);
239 ongoingRestRequestMap.remove(timedoutRequest);
248 stopOrderedFlag = true;
250 while (consumerThread.isAlive()) {
251 ThreadUtilities.sleep(REST_REQUESTOR_WAIT_SLEEP_TIME);
256 * This class is used to start a thread for each request issued.
258 * @author Liam Fallon (liam.fallon@ericsson.com)
260 private class RestRequestRunner implements Runnable {
261 private static final String APPLICATION_JSON = "application/json";
263 // The REST request being processed by this thread
264 private final ApexRestRequest request;
266 // The thread executing the REST request
267 private Thread restRequestThread;
270 * Constructor, initialise the request runner with the request.
272 * @param request the request this runner will issue
274 private RestRequestRunner(final ApexRestRequest request) {
275 this.request = request;
283 // Get the thread for the request
284 restRequestThread = Thread.currentThread();
285 var inputExecutionProperties = request.getExecutionProperties();
286 String url = restConsumerProperties.getUrl();
287 Set<String> names = restConsumerProperties.getKeysFromUrl();
288 if (!names.isEmpty() && inputExecutionProperties != null) {
289 Set<String> inputProperty = inputExecutionProperties.stringPropertyNames();
291 names.stream().map(Optional::of)
292 .forEach(op -> op.filter(inputProperty::contains)
293 .orElseThrow(() -> new ApexEventRuntimeException(
294 "key\"" + op.get() + "\"specified on url \"" + restConsumerProperties.getUrl()
295 + "\"not found in execution properties passed by the current policy")));
297 url = names.stream().reduce(url,
298 (acc, str) -> acc.replace("{" + str + "}", (String) inputExecutionProperties.get(str)));
301 if (restConsumerProperties.getHttpMethod().equals(HttpMethod.PUT)
302 || restConsumerProperties.getHttpMethod().equals(HttpMethod.POST)) {
303 NetLoggerUtil.log(EventType.OUT, CommInfrastructure.REST, url, request.getEvent().toString());
305 // Execute the REST request
306 final String eventJsonString;
307 try (var response = sendEventAsRestRequest(url)) {
308 // Get the event we received
309 eventJsonString = response.readEntity(String.class);
310 NetLoggerUtil.log(EventType.IN, CommInfrastructure.REST, url, eventJsonString);
311 // Match the return code
312 var isPass = httpCodeFilterPattern.matcher(String.valueOf(response.getStatus()));
314 // Check that the request worked
315 if (!isPass.matches()) {
316 final String errorMessage = "reception of event from URL \"" + restConsumerProperties.getUrl()
317 + "\" failed with status code " + response.getStatus();
318 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 LOGGER.info("event from request: {}", request.getEvent());
360 return switch (restConsumerProperties.getHttpMethod()) {
361 case GET -> headers.get();
362 case PUT -> headers.put(Entity.json(request.getEvent()));
363 case POST -> headers.post(Entity.json(request.getEvent()));
364 case DELETE -> headers.delete();