c8a07f234c27787d2888188bc40a575830fd1adc
[policy/apex-pdp.git] /
1 /*-
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
9  *
10  *      http://www.apache.org/licenses/LICENSE-2.0
11  *
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.
17  *
18  * SPDX-License-Identifier: Apache-2.0
19  * ============LICENSE_END=========================================================
20  */
21
22 package org.onap.policy.apex.plugins.event.carrier.restserver;
23
24 import java.util.EnumMap;
25 import java.util.Map;
26 import java.util.Properties;
27 import java.util.concurrent.atomic.AtomicLong;
28 import javax.ws.rs.core.Response;
29 import org.onap.policy.apex.core.infrastructure.threading.ApplicationThreadFactory;
30 import org.onap.policy.apex.core.infrastructure.threading.ThreadUtilities;
31 import org.onap.policy.apex.service.engine.event.ApexEventConsumer;
32 import org.onap.policy.apex.service.engine.event.ApexEventException;
33 import org.onap.policy.apex.service.engine.event.ApexEventReceiver;
34 import org.onap.policy.apex.service.engine.event.PeeredReference;
35 import org.onap.policy.apex.service.engine.event.SynchronousEventCache;
36 import org.onap.policy.apex.service.parameters.eventhandler.EventHandlerParameters;
37 import org.onap.policy.apex.service.parameters.eventhandler.EventHandlerPeeredMode;
38 import org.onap.policy.common.endpoints.http.server.HttpServletServer;
39 import org.onap.policy.common.endpoints.http.server.HttpServletServerFactoryInstance;
40 import org.onap.policy.common.gson.GsonMessageBodyHandler;
41 import org.slf4j.Logger;
42 import org.slf4j.LoggerFactory;
43
44 /**
45  * This class implements an Apex event consumer that receives events from a REST server.
46  *
47  * @author Liam Fallon (liam.fallon@ericsson.com)
48  */
49 public class ApexRestServerConsumer implements ApexEventConsumer, Runnable {
50     // Get a reference to the logger
51     private static final Logger LOGGER = LoggerFactory.getLogger(ApexRestServerConsumer.class);
52
53     // The amount of time to wait in milliseconds between checks that the consumer thread has stopped
54     private static final long REST_SERVER_CONSUMER_WAIT_SLEEP_TIME = 50;
55
56     // The event receiver that will receive events from this consumer
57     private ApexEventReceiver eventReceiver;
58
59     // The name for this consumer
60     private String name = null;
61
62     // The peer references for this event handler
63     private Map<EventHandlerPeeredMode, PeeredReference> peerReferenceMap = new EnumMap<>(EventHandlerPeeredMode.class);
64
65     // The consumer thread and stopping flag
66     private Thread consumerThread;
67     private boolean stopOrderedFlag = false;
68
69     // The local HTTP server to use for REST call reception if we are running a local Grizzly server
70     private HttpServletServer server;
71
72     // Holds the next identifier for event execution.
73     private static AtomicLong nextExecutionID = new AtomicLong(0L);
74
75     /**
76      * Private utility to get the next candidate value for a Execution ID. This value will always be unique in a single
77      * JVM
78      *
79      * @return the next candidate value for a Execution ID
80      */
81     private static synchronized long getNextExecutionId() {
82         return nextExecutionID.getAndIncrement();
83     }
84
85     /**
86      * {@inheritDoc}.
87      */
88     @Override
89     public void init(final String consumerName, final EventHandlerParameters consumerParameters,
90             final ApexEventReceiver incomingEventReceiver) throws ApexEventException {
91         this.eventReceiver = incomingEventReceiver;
92         this.name = consumerName;
93
94         // Check and get the REST Properties
95         if (!(consumerParameters.getCarrierTechnologyParameters() instanceof RestServerCarrierTechnologyParameters)) {
96             final String errorMessage =
97                     "specified consumer properties are not applicable to REST Server consumer (" + this.name + ")";
98             LOGGER.warn(errorMessage);
99             throw new ApexEventException(errorMessage);
100         }
101
102         // The REST parameters read from the parameter service
103         RestServerCarrierTechnologyParameters restConsumerProperties =
104                 (RestServerCarrierTechnologyParameters) consumerParameters.getCarrierTechnologyParameters();
105
106         // Check if we are in synchronous mode
107         if (!consumerParameters.isPeeredMode(EventHandlerPeeredMode.SYNCHRONOUS)) {
108             final String errorMessage =
109                     "REST Server consumer (" + this.name + ") must run in synchronous mode with a REST Server producer";
110             LOGGER.warn(errorMessage);
111             throw new ApexEventException(errorMessage);
112         }
113
114         // Check if we're in standalone mode
115         if (restConsumerProperties.isStandalone()) {
116             // Check if host and port are defined
117             if (restConsumerProperties.getHost() == null || restConsumerProperties.getPort() == -1) {
118                 final String errorMessage =
119                         "the parameters \"host\" and \"port\" must be defined for REST Server consumer (" + this.name
120                                 + ") in standalone mode";
121                 LOGGER.warn(errorMessage);
122                 throw new ApexEventException(errorMessage);
123             }
124
125             // Instantiate the standalone server
126             LOGGER.info("Creating the Apex Rest Server");
127             createServer(restConsumerProperties);
128             server.start();
129             while (!server.isAlive()) {
130                 ThreadUtilities.sleep(REST_SERVER_CONSUMER_WAIT_SLEEP_TIME);
131             }
132         }
133
134         // Register this consumer with the REST server end point
135         RestServerEndpoint.registerApexRestServerConsumer(this.name, this);
136     }
137
138     private void createServer(RestServerCarrierTechnologyParameters restConsumerProperties) {
139
140         server = HttpServletServerFactoryInstance.getServerFactory().build(
141             restConsumerProperties.getName(),
142             restConsumerProperties.isHttps(),
143             restConsumerProperties.getHost(),
144             restConsumerProperties.getPort(), null, true, false);
145         if (restConsumerProperties.isAaf()) {
146             server.addFilterClass(null, ApexRestServerAafFilter.class.getName());
147         }
148         server.addServletClass(null, RestServerEndpoint.class.getName());
149         server.addServletClass(null, AccessControlFilter.class.getName());
150         server.setSerializationProvider(GsonMessageBodyHandler.class.getName());
151         if (null != restConsumerProperties.getUserName()
152             && null != restConsumerProperties.getPassword()) {
153             server.setBasicAuthentication(restConsumerProperties.getUserName(),
154                 restConsumerProperties.getPassword(), null);
155         }
156     }
157
158     /**
159      * {@inheritDoc}.
160      */
161     @Override
162     public void start() {
163         // Configure and start the event reception thread
164         final String threadName = this.getClass().getName() + ":" + this.name;
165         consumerThread = new ApplicationThreadFactory(threadName).newThread(this);
166         consumerThread.setDaemon(true);
167         consumerThread.start();
168     }
169
170     /**
171      * {@inheritDoc}.
172      */
173     @Override
174     public String getName() {
175         return name;
176     }
177
178     /**
179      * {@inheritDoc}.
180      */
181     @Override
182     public PeeredReference getPeeredReference(final EventHandlerPeeredMode peeredMode) {
183         return peerReferenceMap.get(peeredMode);
184     }
185
186     /**
187      * {@inheritDoc}.
188      */
189     @Override
190     public void setPeeredReference(final EventHandlerPeeredMode peeredMode, final PeeredReference peeredReference) {
191         peerReferenceMap.put(peeredMode, peeredReference);
192     }
193
194     /**
195      * Receive an event for processing in Apex.
196      *
197      * @param event the event to receive
198      * @return the response from Apex
199      */
200     public Response receiveEvent(final String event) {
201         // Get an execution ID for the event
202         final long executionId = getNextExecutionId();
203
204         if (LOGGER.isDebugEnabled()) {
205             String message = name + ": sending event " + name + '_' + executionId + " to Apex, event=" + event;
206             LOGGER.debug(message);
207         }
208
209         try {
210             // Send the event into Apex
211             eventReceiver.receiveEvent(executionId, new Properties(), event);
212         } catch (final Exception e) {
213             final String errorMessage = "error receiving events on event consumer " + name + ", " + e.getMessage();
214             LOGGER.warn(errorMessage, e);
215             return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode())
216                     .entity("{'errorMessage', '" + errorMessage + "'}").build();
217         }
218
219         final SynchronousEventCache synchronousEventCache =
220                 (SynchronousEventCache) peerReferenceMap.get(EventHandlerPeeredMode.SYNCHRONOUS);
221         // Wait until the event is in the cache of events sent to apex
222         do {
223             ThreadUtilities.sleep(REST_SERVER_CONSUMER_WAIT_SLEEP_TIME);
224         }
225         while (!synchronousEventCache.existsEventToApex(executionId));
226
227         // Now wait for the reply or for the event to time put
228         do {
229             ThreadUtilities.sleep(REST_SERVER_CONSUMER_WAIT_SLEEP_TIME);
230
231             // Check if we have received an answer from Apex
232             if (synchronousEventCache.existsEventFromApex(executionId)) {
233                 // We have received a response event, read and remove the response event and remove the sent event from
234                 // the cache
235                 final Object responseEvent = synchronousEventCache.removeCachedEventFromApexIfExists(executionId);
236                 synchronousEventCache.removeCachedEventToApexIfExists(executionId);
237
238                 // Return the event as a response to the call
239                 return Response.status(Response.Status.OK.getStatusCode()).entity(responseEvent.toString()).build();
240             }
241         }
242         while (synchronousEventCache.existsEventToApex(executionId));
243
244         // The event timed out
245         final String errorMessage = "processing of event on event consumer " + name + " timed out, event=" + event;
246         LOGGER.warn(errorMessage);
247         return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode())
248                 .entity("{'errorMessage', '" + errorMessage + "'}").build();
249     }
250
251     /**
252      * {@inheritDoc}.
253      */
254     @Override
255     public void run() {
256         // Keep the consumer thread alive until it is shut down. We do not currently do anything in the thread but may
257         // do supervision in the future
258         while (consumerThread.isAlive() && !stopOrderedFlag) {
259             ThreadUtilities.sleep(REST_SERVER_CONSUMER_WAIT_SLEEP_TIME);
260         }
261
262         if (server != null) {
263             server.shutdown();
264         }
265     }
266
267     /**
268      * {@inheritDoc}.
269      */
270     @Override
271     public void stop() {
272         stopOrderedFlag = true;
273
274         while (consumerThread.isAlive()) {
275             ThreadUtilities.sleep(REST_SERVER_CONSUMER_WAIT_SLEEP_TIME);
276         }
277         if (server != null) {
278             server.stop();
279         }
280     }
281 }