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
9 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 * SPDX-License-Identifier: Apache-2.0
18 * ============LICENSE_END=========================================================
21 package org.onap.policy.apex.plugins.event.carrier.restserver;
24 import java.util.EnumMap;
26 import java.util.concurrent.atomic.AtomicLong;
28 import javax.ws.rs.core.Response;
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;
46 * This class implements an Apex event consumer that receives events from a REST server.
48 * @author Liam Fallon (liam.fallon@ericsson.com)
50 public class ApexRestServerConsumer implements ApexEventConsumer, Runnable {
51 // Get a reference to the logger
52 private static final Logger LOGGER = LoggerFactory.getLogger(ApexRestServerConsumer.class);
54 private static final String BASE_URI_TEMPLATE = "http://%s:%d/apex";
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;
59 // The event receiver that will receive events from this consumer
60 private ApexEventReceiver eventReceiver;
62 // The name for this consumer
63 private String name = null;
65 // The peer references for this event handler
66 private Map<EventHandlerPeeredMode, PeeredReference> peerReferenceMap = new EnumMap<>(EventHandlerPeeredMode.class);
68 // The consumer thread and stopping flag
69 private Thread consumerThread;
70 private boolean stopOrderedFlag = false;
72 // The local HTTP server to use for REST call reception if we are running a local Grizzly server
73 private HttpServer server;
75 // Holds the next identifier for event execution.
76 private static AtomicLong nextExecutionID = new AtomicLong(0L);
79 * Private utility to get the next candidate value for a Execution ID. This value will always be unique in a single
82 * @return the next candidate value for a Execution ID
84 private static synchronized long getNextExecutionId() {
85 return nextExecutionID.getAndIncrement();
91 * @see org.onap.policy.apex.service.engine.event.ApexEventConsumer#init(java.lang.String,
92 * org.onap.policy.apex.service.parameters.eventhandler.EventHandlerParameters,
93 * org.onap.policy.apex.service.engine.event.ApexEventReceiver)
96 public void init(final String consumerName, final EventHandlerParameters consumerParameters,
97 final ApexEventReceiver incomingEventReceiver) throws ApexEventException {
98 this.eventReceiver = incomingEventReceiver;
99 this.name = consumerName;
101 // Check and get the REST Properties
102 if (!(consumerParameters.getCarrierTechnologyParameters() instanceof RestServerCarrierTechnologyParameters)) {
103 final String errorMessage =
104 "specified consumer properties are not applicable to REST Server consumer (" + this.name + ")";
105 LOGGER.warn(errorMessage);
106 throw new ApexEventException(errorMessage);
109 // The REST parameters read from the parameter service
110 RestServerCarrierTechnologyParameters restConsumerProperties =
111 (RestServerCarrierTechnologyParameters) consumerParameters.getCarrierTechnologyParameters();
113 // Check if we are in synchronous mode
114 if (!consumerParameters.isPeeredMode(EventHandlerPeeredMode.SYNCHRONOUS)) {
115 final String errorMessage =
116 "REST Server consumer (" + this.name + ") must run in synchronous mode with a REST Server producer";
117 LOGGER.warn(errorMessage);
118 throw new ApexEventException(errorMessage);
121 // Check if we're in standalone mode
122 if (restConsumerProperties.isStandalone()) {
123 // Check if host and port are defined
124 if (restConsumerProperties.getHost() == null || restConsumerProperties.getPort() == -1) {
125 final String errorMessage =
126 "the parameters \"host\" and \"port\" must be defined for REST Server consumer (" + this.name
127 + ") in standalone mode";
128 LOGGER.warn(errorMessage);
129 throw new ApexEventException(errorMessage);
132 // Compose the URI for the standalone server
133 final String baseUrl = String.format(BASE_URI_TEMPLATE, restConsumerProperties.getHost(),
134 restConsumerProperties.getPort());
136 // Instantiate the standalone server
137 final ResourceConfig rc = new ResourceConfig(RestServerEndpoint.class, AccessControlFilter.class);
138 server = GrizzlyHttpServerFactory.createHttpServer(URI.create(baseUrl), rc);
140 while (!server.isStarted()) {
141 ThreadUtilities.sleep(REST_SERVER_CONSUMER_WAIT_SLEEP_TIME);
145 // Register this consumer with the REST server end point
146 RestServerEndpoint.registerApexRestServerConsumer(this.name, this);
152 * @see org.onap.policy.apex.service.engine.event.ApexEventConsumer#start()
155 public void start() {
156 // Configure and start the event reception thread
157 final String threadName = this.getClass().getName() + ":" + this.name;
158 consumerThread = new ApplicationThreadFactory(threadName).newThread(this);
159 consumerThread.setDaemon(true);
160 consumerThread.start();
166 * @see org.onap.policy.apex.service.engine.event.ApexEventConsumer#getName()
169 public String getName() {
176 * @see org.onap.policy.apex.service.engine.event.ApexEventConsumer#getPeeredReference(org.onap.policy.apex.service.
177 * parameters. eventhandler.EventHandlerPeeredMode)
180 public PeeredReference getPeeredReference(final EventHandlerPeeredMode peeredMode) {
181 return peerReferenceMap.get(peeredMode);
187 * @see org.onap.policy.apex.service.engine.event.ApexEventConsumer#setPeeredReference(org.onap.policy.apex.service.
188 * parameters. eventhandler.EventHandlerPeeredMode, org.onap.policy.apex.service.engine.event.PeeredReference)
191 public void setPeeredReference(final EventHandlerPeeredMode peeredMode, final PeeredReference peeredReference) {
192 peerReferenceMap.put(peeredMode, peeredReference);
196 * Receive an event for processing in Apex.
198 * @param event the event to receive
199 * @return the response from Apex
201 public Response receiveEvent(final String event) {
202 // Get an execution ID for the event
203 final long executionId = getNextExecutionId();
205 if (LOGGER.isDebugEnabled()) {
206 String message = name + ": sending event " + name + '_' + executionId + " to Apex, event=" + event;
207 LOGGER.debug(message);
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, e);
216 return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode())
217 .entity("{'errorMessage', '" + errorMessage + "'}").build();
220 final SynchronousEventCache synchronousEventCache =
221 (SynchronousEventCache) peerReferenceMap.get(EventHandlerPeeredMode.SYNCHRONOUS);
222 // Wait until the event is in the cache of events sent to apex
224 ThreadUtilities.sleep(REST_SERVER_CONSUMER_WAIT_SLEEP_TIME);
226 while (!synchronousEventCache.existsEventToApex(executionId));
228 // Now wait for the reply or for the event to time put
230 ThreadUtilities.sleep(REST_SERVER_CONSUMER_WAIT_SLEEP_TIME);
232 // Check if we have received an answer from Apex
233 if (synchronousEventCache.existsEventFromApex(executionId)) {
234 // We have received a response event, read and remove the response event and remove the sent event from
236 final Object responseEvent = synchronousEventCache.removeCachedEventFromApexIfExists(executionId);
237 synchronousEventCache.removeCachedEventToApexIfExists(executionId);
239 // Return the event as a response to the call
240 return Response.status(Response.Status.OK.getStatusCode()).entity(responseEvent.toString()).build();
243 while (synchronousEventCache.existsEventToApex(executionId));
245 // The event timed out
246 final String errorMessage = "processing of event on event consumer " + name + " timed out, event=" + event;
247 LOGGER.warn(errorMessage);
248 return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode())
249 .entity("{'errorMessage', '" + errorMessage + "'}").build();
255 * @see java.lang.Runnable#run()
259 // Keep the consumer thread alive until it is shut down. We do not currently do anything in the thread but may
260 // do supervision in the future
261 while (consumerThread.isAlive() && !stopOrderedFlag) {
262 ThreadUtilities.sleep(REST_SERVER_CONSUMER_WAIT_SLEEP_TIME);
265 if (server != null) {
273 * @see org.onap.policy.apex.apps.uservice.consumer.ApexEventConsumer#stop()
277 stopOrderedFlag = true;
279 while (consumerThread.isAlive()) {
280 ThreadUtilities.sleep(REST_SERVER_CONSUMER_WAIT_SLEEP_TIME);