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