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