57c14b946700c86f4a5ba745247059ee222f2324
[policy/apex-pdp.git] /
1 /*-
2  * ============LICENSE_START=======================================================
3  *  Copyright (C) 2016-2018 Ericsson. All rights reserved.
4  * ================================================================================
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  *      http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  *
17  * SPDX-License-Identifier: Apache-2.0
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.onap.policy.apex.plugins.event.carrier.restrequestor;
22
23 import java.net.URL;
24 import java.util.ArrayList;
25 import java.util.Arrays;
26 import java.util.EnumMap;
27 import java.util.List;
28 import java.util.Map;
29 import java.util.Map.Entry;
30 import java.util.concurrent.BlockingQueue;
31 import java.util.concurrent.ConcurrentHashMap;
32 import java.util.concurrent.LinkedBlockingQueue;
33 import java.util.concurrent.TimeUnit;
34
35 import javax.ws.rs.client.Client;
36 import javax.ws.rs.client.ClientBuilder;
37 import javax.ws.rs.client.Entity;
38 import javax.ws.rs.core.Response;
39
40 import org.onap.policy.apex.core.infrastructure.threading.ApplicationThreadFactory;
41 import org.onap.policy.apex.core.infrastructure.threading.ThreadUtilities;
42 import org.onap.policy.apex.service.engine.event.ApexEventConsumer;
43 import org.onap.policy.apex.service.engine.event.ApexEventException;
44 import org.onap.policy.apex.service.engine.event.ApexEventReceiver;
45 import org.onap.policy.apex.service.engine.event.ApexEventRuntimeException;
46 import org.onap.policy.apex.service.engine.event.PeeredReference;
47 import org.onap.policy.apex.service.parameters.eventhandler.EventHandlerParameters;
48 import org.onap.policy.apex.service.parameters.eventhandler.EventHandlerPeeredMode;
49 import org.slf4j.Logger;
50 import org.slf4j.LoggerFactory;
51
52 /**
53  * This class implements an Apex event consumer that issues a REST request and returns the REST response to APEX as an
54  * event.
55  *
56  * @author Liam Fallon (liam.fallon@ericsson.com)
57  */
58 public class ApexRestRequestorConsumer implements ApexEventConsumer, Runnable {
59     // Get a reference to the logger
60     private static final Logger LOGGER = LoggerFactory.getLogger(ApexRestRequestorConsumer.class);
61
62     // The amount of time to wait in milliseconds between checks that the consumer thread has
63     // stopped
64     private static final long REST_REQUESTOR_WAIT_SLEEP_TIME = 50;
65
66     // The REST parameters read from the parameter service
67     private RestRequestorCarrierTechnologyParameters restConsumerProperties;
68
69     // The timeout for REST requests
70     private long restRequestTimeout = RestRequestorCarrierTechnologyParameters.DEFAULT_REST_REQUEST_TIMEOUT;
71
72     // The event receiver that will receive events from this consumer
73     private ApexEventReceiver eventReceiver;
74
75     // The HTTP client that makes a REST call to get an input event for Apex
76     private Client client;
77
78     // The name for this consumer
79     private String name = null;
80
81     // The peer references for this event handler
82     private Map<EventHandlerPeeredMode, PeeredReference> peerReferenceMap = new EnumMap<>(EventHandlerPeeredMode.class);
83
84     // The consumer thread and stopping flag
85     private Thread consumerThread;
86     private boolean stopOrderedFlag = false;
87
88     // Temporary request holder for incoming REST requests
89     private final BlockingQueue<ApexRestRequest> incomingRestRequestQueue = new LinkedBlockingQueue<>();
90
91     // Map of ongoing REST request threads indexed by the time they started at
92     private final Map<ApexRestRequest, RestRequestRunner> ongoingRestRequestMap = new ConcurrentHashMap<>();
93
94     // The number of events received to date
95     private Object eventsReceivedLock = new Object();
96     private Integer eventsReceived = 0;
97
98     // The number of the next request runner thread
99     private static long nextRequestRunnerThreadNo = 0;
100
101     @Override
102     public void init(final String consumerName, final EventHandlerParameters consumerParameters,
103                     final ApexEventReceiver incomingEventReceiver) throws ApexEventException {
104         this.eventReceiver = incomingEventReceiver;
105         this.name = consumerName;
106
107         // Check and get the REST Properties
108         if (!(consumerParameters
109                         .getCarrierTechnologyParameters() instanceof RestRequestorCarrierTechnologyParameters)) {
110             final String errorMessage = "specified consumer properties are not applicable to REST Requestor consumer ("
111                             + this.name + ")";
112             LOGGER.warn(errorMessage);
113             throw new ApexEventException(errorMessage);
114         }
115         restConsumerProperties = (RestRequestorCarrierTechnologyParameters) consumerParameters
116                         .getCarrierTechnologyParameters();
117
118         // Check if we are in peered mode
119         if (!consumerParameters.isPeeredMode(EventHandlerPeeredMode.REQUESTOR)) {
120             final String errorMessage = "REST Requestor consumer (" + this.name
121                             + ") must run in peered requestor mode with a REST Requestor producer";
122             LOGGER.warn(errorMessage);
123             throw new ApexEventException(errorMessage);
124         }
125
126         // Check if the HTTP method has been set
127         if (restConsumerProperties.getHttpMethod() == null) {
128             restConsumerProperties
129                             .setHttpMethod(RestRequestorCarrierTechnologyParameters.DEFAULT_REQUESTOR_HTTP_METHOD);
130         }
131
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             LOGGER.warn(errorMessage);
136             throw new ApexEventException(errorMessage);
137         }
138
139         // Check if the HTTP URL is valid
140         try {
141             new URL(restConsumerProperties.getUrl());
142         } catch (final Exception e) {
143             final String errorMessage = "invalid URL has been specified on REST Requestor consumer (" + this.name + ")";
144             LOGGER.warn(errorMessage);
145             throw new ApexEventException(errorMessage, e);
146         }
147
148         // Set the requestor timeout
149         if (consumerParameters.getPeerTimeout(EventHandlerPeeredMode.REQUESTOR) != 0) {
150             restRequestTimeout = consumerParameters.getPeerTimeout(EventHandlerPeeredMode.REQUESTOR);
151         }
152
153         // Check if HTTP headers has been set
154         if (restConsumerProperties.checkHttpHeadersSet()) {
155             LOGGER.debug("REST Requestor consumer has http headers ({}): {}", this.name,
156                             Arrays.deepToString(restConsumerProperties.getHttpHeaders()));
157         }
158
159         // Initialize the HTTP client
160         client = ClientBuilder.newClient();
161     }
162
163     /**
164      * Receive an incoming REST request from the peered REST Requestor producer and queue it.
165      *
166      * @param restRequest the incoming rest request to queue
167      * @throws ApexEventRuntimeException on queueing errors
168      */
169     public void processRestRequest(final ApexRestRequest restRequest) {
170         // Push the event onto the queue for handling
171         try {
172             incomingRestRequestQueue.add(restRequest);
173         } catch (final Exception requestException) {
174             final String errorMessage = "could not queue request \"" + restRequest + "\" on REST Requestor consumer ("
175                             + this.name + ")";
176             LOGGER.warn(errorMessage, requestException);
177             throw new ApexEventRuntimeException(errorMessage);
178         }
179     }
180
181     /*
182      * (non-Javadoc)
183      *
184      * @see org.onap.policy.apex.service.engine.event.ApexEventConsumer#start()
185      */
186     @Override
187     public void start() {
188         // Configure and start the event reception thread
189         final String threadName = this.getClass().getName() + ":" + this.name;
190         consumerThread = new ApplicationThreadFactory(threadName).newThread(this);
191         consumerThread.setDaemon(true);
192         consumerThread.start();
193     }
194
195     /*
196      * (non-Javadoc)
197      *
198      * @see org.onap.policy.apex.service.engine.event.ApexEventConsumer#getName()
199      */
200     @Override
201     public String getName() {
202         return name;
203     }
204
205     /**
206      * Get the number of events received to date.
207      *
208      * @return the number of events received
209      */
210     public int getEventsReceived() {
211         return eventsReceived;
212     }
213
214     /*
215      * (non-Javadoc)
216      *
217      * @see org.onap.policy.apex.service.engine.event.ApexEventConsumer#getPeeredReference(org.onap.
218      * policy.apex.service. parameters.eventhandler.EventHandlerPeeredMode)
219      */
220     @Override
221     public PeeredReference getPeeredReference(final EventHandlerPeeredMode peeredMode) {
222         return peerReferenceMap.get(peeredMode);
223     }
224
225     /*
226      * (non-Javadoc)
227      *
228      * @see org.onap.policy.apex.service.engine.event.ApexEventConsumer#setPeeredReference(org.onap.
229      * policy.apex.service. parameters.eventhandler.EventHandlerPeeredMode,
230      * org.onap.policy.apex.service.engine.event.PeeredReference)
231      */
232     @Override
233     public void setPeeredReference(final EventHandlerPeeredMode peeredMode, final PeeredReference peeredReference) {
234         peerReferenceMap.put(peeredMode, peeredReference);
235     }
236
237     /*
238      * (non-Javadoc)
239      *
240      * @see java.lang.Runnable#run()
241      */
242     @Override
243     public void run() {
244         // The endless loop that receives events using REST calls
245         while (consumerThread.isAlive() && !stopOrderedFlag) {
246             try {
247                 // Take the next event from the queue
248                 final ApexRestRequest restRequest = incomingRestRequestQueue.poll(REST_REQUESTOR_WAIT_SLEEP_TIME,
249                                 TimeUnit.MILLISECONDS);
250                 if (restRequest == null) {
251                     // Poll timed out, check for request timeouts
252                     timeoutExpiredRequests();
253                     continue;
254                 }
255
256                 // Set the time stamp of the REST request
257                 restRequest.setTimestamp(System.currentTimeMillis());
258
259                 // Create a thread to process the REST request and place it on the map of ongoing
260                 // requests
261                 final RestRequestRunner restRequestRunner = new RestRequestRunner(restRequest);
262                 ongoingRestRequestMap.put(restRequest, restRequestRunner);
263
264                 // Start execution of the request
265                 final Thread restRequestRunnerThread = new Thread(restRequestRunner);
266                 restRequestRunnerThread.setName("RestRequestRunner_" + nextRequestRunnerThreadNo);
267                 restRequestRunnerThread.start();
268             } catch (final InterruptedException e) {
269                 LOGGER.debug("Thread interrupted, Reason {}", e.getMessage());
270                 Thread.currentThread().interrupt();
271             }
272         }
273
274         client.close();
275     }
276
277     /**
278      * This method times out REST requests that have expired.
279      */
280     private void timeoutExpiredRequests() {
281         // Hold a list of timed out requests
282         final List<ApexRestRequest> timedoutRequestList = new ArrayList<>();
283
284         // Check for timeouts
285         for (final Entry<ApexRestRequest, RestRequestRunner> requestEntry : ongoingRestRequestMap.entrySet()) {
286             if (System.currentTimeMillis() - requestEntry.getKey().getTimestamp() > restRequestTimeout) {
287                 requestEntry.getValue().stop();
288                 timedoutRequestList.add(requestEntry.getKey());
289             }
290         }
291
292         // Interrupt timed out requests and remove them from the ongoing map
293         for (final ApexRestRequest timedoutRequest : timedoutRequestList) {
294             final String errorMessage = "REST Requestor consumer (" + this.name + "), REST request timed out: "
295                             + timedoutRequest;
296             LOGGER.warn(errorMessage);
297
298             ongoingRestRequestMap.remove(timedoutRequest);
299         }
300     }
301
302     /*
303      * (non-Javadoc)
304      *
305      * @see org.onap.policy.apex.apps.uservice.producer.ApexEventConsumer#stop()
306      */
307     @Override
308     public void stop() {
309         stopOrderedFlag = true;
310
311         while (consumerThread.isAlive()) {
312             ThreadUtilities.sleep(REST_REQUESTOR_WAIT_SLEEP_TIME);
313         }
314     }
315
316     /**
317      * This class is used to start a thread for each request issued.
318      *
319      * @author Liam Fallon (liam.fallon@ericsson.com)
320      */
321     private class RestRequestRunner implements Runnable {
322         private static final String APPLICATION_JSON = "application/json";
323
324         // The REST request being processed by this thread
325         private final ApexRestRequest request;
326
327         // The thread executing the REST request
328         private Thread restRequestThread;
329
330         /**
331          * Constructor, initialise the request runner with the request.
332          *
333          * @param request the request this runner will issue
334          */
335         private RestRequestRunner(final ApexRestRequest request) {
336             this.request = request;
337         }
338
339         /*
340          * (non-Javadoc)
341          *
342          * @see java.lang.Runnable#run()
343          */
344         @Override
345         public void run() {
346             // Get the thread for the request
347             restRequestThread = Thread.currentThread();
348
349             try {
350                 // Execute the REST request
351                 final Response response = sendEventAsRestRequest();
352
353                 // Check that the event request worked
354                 if (!Response.Status.Family.familyOf(response.getStatus()).equals(Response.Status.Family.SUCCESSFUL)) {
355                     final String errorMessage = "reception of response to \"" + request + "\" from URL \""
356                                     + restConsumerProperties.getUrl() + "\" failed with status code "
357                                     + response.getStatus() + " and message \"" + response.readEntity(String.class)
358                                     + "\"";
359                     throw new ApexEventRuntimeException(errorMessage);
360                 }
361
362                 // Get the event we received
363                 final String eventJsonString = response.readEntity(String.class);
364
365                 // Check there is content
366                 if (eventJsonString == null || eventJsonString.trim().length() == 0) {
367                     final String errorMessage = "received an enpty response to \"" + request + "\" from URL \""
368                                     + restConsumerProperties.getUrl() + "\"";
369                     throw new ApexEventRuntimeException(errorMessage);
370                 }
371
372                 // Send the event into Apex
373                 eventReceiver.receiveEvent(request.getExecutionId(), eventJsonString);
374
375                 synchronized (eventsReceivedLock) {
376                     eventsReceived++;
377                 }
378             } catch (final Exception e) {
379                 LOGGER.warn("error receiving events on thread {}", consumerThread.getName(), e);
380             } finally {
381                 // Remove the request from the map of ongoing requests
382                 ongoingRestRequestMap.remove(request);
383             }
384         }
385
386         /**
387          * Stop the REST request.
388          */
389         private void stop() {
390             restRequestThread.interrupt();
391         }
392
393         /**
394          * Execute the REST request.
395          *
396          * 
397          * @return the response to the REST request
398          */
399         public Response sendEventAsRestRequest() {
400             switch (restConsumerProperties.getHttpMethod()) {
401                 case GET:
402                     return client.target(restConsumerProperties.getUrl()).request(APPLICATION_JSON)
403                                     .headers(restConsumerProperties.getHttpHeadersAsMultivaluedMap()).get();
404
405                 case PUT:
406                     return client.target(restConsumerProperties.getUrl()).request(APPLICATION_JSON)
407                                     .headers(restConsumerProperties.getHttpHeadersAsMultivaluedMap())
408                                     .put(Entity.json(request.getEvent()));
409
410                 case POST:
411                     return client.target(restConsumerProperties.getUrl()).request(APPLICATION_JSON)
412                                     .headers(restConsumerProperties.getHttpHeadersAsMultivaluedMap())
413                                     .post(Entity.json(request.getEvent()));
414
415                 case DELETE:
416                     return client.target(restConsumerProperties.getUrl()).request(APPLICATION_JSON)
417                                     .headers(restConsumerProperties.getHttpHeadersAsMultivaluedMap()).delete();
418
419                 default:
420                     break;
421             }
422
423             return null;
424         }
425     }
426 }