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.service.engine.engdep;
23 import java.util.Collection;
24 import java.util.List;
25 import java.util.concurrent.BlockingQueue;
26 import java.util.concurrent.LinkedBlockingDeque;
27 import java.util.concurrent.TimeUnit;
29 import org.java_websocket.WebSocket;
30 import org.onap.policy.apex.core.infrastructure.messaging.MessageHolder;
31 import org.onap.policy.apex.core.infrastructure.messaging.MessageListener;
32 import org.onap.policy.apex.core.infrastructure.messaging.impl.ws.messageblock.MessageBlock;
33 import org.onap.policy.apex.core.infrastructure.messaging.util.MessagingUtils;
34 import org.onap.policy.apex.core.infrastructure.threading.ThreadUtilities;
35 import org.onap.policy.apex.core.protocols.Message;
36 import org.onap.policy.apex.core.protocols.engdep.EngDepAction;
37 import org.onap.policy.apex.core.protocols.engdep.messages.EngineServiceInfoResponse;
38 import org.onap.policy.apex.core.protocols.engdep.messages.GetEngineInfo;
39 import org.onap.policy.apex.core.protocols.engdep.messages.GetEngineServiceInfo;
40 import org.onap.policy.apex.core.protocols.engdep.messages.GetEngineStatus;
41 import org.onap.policy.apex.core.protocols.engdep.messages.Response;
42 import org.onap.policy.apex.core.protocols.engdep.messages.StartEngine;
43 import org.onap.policy.apex.core.protocols.engdep.messages.StartPeriodicEvents;
44 import org.onap.policy.apex.core.protocols.engdep.messages.StopEngine;
45 import org.onap.policy.apex.core.protocols.engdep.messages.StopPeriodicEvents;
46 import org.onap.policy.apex.core.protocols.engdep.messages.UpdateModel;
47 import org.onap.policy.apex.model.basicmodel.concepts.ApexException;
48 import org.onap.policy.apex.model.basicmodel.concepts.AxArtifactKey;
49 import org.onap.policy.apex.service.engine.runtime.EngineService;
50 import org.slf4j.ext.XLogger;
51 import org.slf4j.ext.XLoggerFactory;
53 import com.google.common.eventbus.Subscribe;
56 * The listener interface for receiving engDepMessage events. The class that is interested in
57 * processing a engDepMessage event implements this interface, and the object created with that
58 * class is registered with a component using the component's <code>addEngDepMessageListener</code>
59 * method. When the engDepMessage event occurs, that object's appropriate method is invoked.
61 * This class uses a queue to buffer incoming messages. When the listener is called, it places the
62 * incoming message on the queue. A thread runs which removes the messages from the queue and
63 * forwards them to the Apex engine.
65 * @author Sajeevan Achuthan (sajeevan.achuthan@ericsson.com)
67 public class EngDepMessageListener implements MessageListener<Message>, Runnable {
68 private static final int LISTENER_STOP_WAIT_INTERVAL = 10;
70 private static final XLogger LOGGER = XLoggerFactory.getXLogger(EngDepMessageListener.class);
72 // The timeout to wait between queue poll timeouts in milliseconds
73 private static final long QUEUE_POLL_TIMEOUT = 50;
75 // The Apex service itself
76 private final EngineService apexService;
78 // The message listener thread and stopping flag
79 private Thread messageListenerThread;
80 private boolean stopOrderedFlag = false;
82 // The message queue is used to hold messages prior to forwarding to Apex
83 private final BlockingQueue<MessageBlock<Message>> messageQueue = new LinkedBlockingDeque<>();
86 * Instantiates a new EngDep message listener for listening for messages coming in from the
87 * Deployment client. The <code>apexService</code> is the Apex service to send the messages
90 * @param apexService the Apex engine service
92 protected EngDepMessageListener(final EngineService apexService) {
93 this.apexService = apexService;
97 * This method is an implementation of the message listener. It receives a message and places it
98 * on the queue for processing by the message listening thread.
100 * @param data the data
101 * @see org.onap.policy.apex.core.infrastructure.messaging.MessageListener#onMessage
102 * (org.onap.policy.apex.core.infrastructure.messaging.impl.ws.data.Data)
106 public void onMessage(final MessageBlock<Message> data) {
107 if (LOGGER.isDebugEnabled()) {
108 LOGGER.debug("message received from client application {} port {}",
109 data.getConnection().getRemoteSocketAddress().getAddress(),
110 data.getConnection().getRemoteSocketAddress().getPort());
112 messageQueue.add(data);
118 * @see org.onap.policy.apex.core.infrastructure.messaging.MessageListener#onMessage(java.lang.
122 public void onMessage(final String messageString) {
123 throw new UnsupportedOperationException("String messages are not supported on the EngDep protocol");
127 * This method gets a new message listening thread from the thread factory and starts it.
129 public void startProcessorThread() {
131 messageListenerThread = new Thread(this);
132 messageListenerThread.setDaemon(true);
133 messageListenerThread.start();
138 * Stops the message listening threads.
140 public void stopProcessorThreads() {
142 stopOrderedFlag = true;
144 while (messageListenerThread.isAlive()) {
145 ThreadUtilities.sleep(LISTENER_STOP_WAIT_INTERVAL);
151 * Runs the message listening thread. Here, the messages come in on the message queue and are
152 * processed one by one
156 // Take messages off the queue and forward them to the Apex engine
157 while (messageListenerThread.isAlive() && !stopOrderedFlag) {
159 final MessageBlock<Message> data = messageQueue.poll(QUEUE_POLL_TIMEOUT, TimeUnit.MILLISECONDS);
161 final List<Message> messages = data.getMessages();
162 for (final Message message : messages) {
163 handleMessage(message, data.getConnection());
166 } catch (final InterruptedException e) {
167 LOGGER.debug("message listener execution has been interrupted");
174 * This method handles EngDep messages as they come in. It uses the inevitable switch statement
175 * to handle the messages.
177 * @param message the incoming EngDep message
178 * @param webSocket the web socket on which the message came in
180 private void handleMessage(final Message message, final WebSocket webSocket) {
181 LOGGER.entry(webSocket.getRemoteSocketAddress().toString());
182 if (message.getAction() == null) {
183 // This is a response message
188 LOGGER.debug("Manager action {} being applied to engine", message.getAction());
190 // Get and check the incoming action for validity
191 EngDepAction enDepAction = null;
192 if (message.getAction() instanceof EngDepAction) {
193 enDepAction = (EngDepAction) message.getAction();
195 throw new ApexException(message.getAction().getClass().getName()
196 + "action on received message invalid, action must be of type \"EnDepAction\"");
199 // Handle each incoming message using the inevitable switch statement for the EngDep
201 switch (enDepAction) {
202 case GET_ENGINE_SERVICE_INFO:
203 final GetEngineServiceInfo engineServiceInformationMessage = (GetEngineServiceInfo) message;
204 LOGGER.debug("getting engine service information for engine service " + apexService.getKey().getID()
206 // Send a reply with the engine service information
207 sendServiceInfoReply(webSocket, engineServiceInformationMessage, apexService.getKey(),
208 apexService.getEngineKeys(), apexService.getApexModelKey());
210 "returned engine service information for engine service " + apexService.getKey().getID());
214 final UpdateModel updateModelMessage = (UpdateModel) message;
215 LOGGER.debug("updating model in engine {} . . .", updateModelMessage.getTarget().getID());
217 apexService.updateModel(updateModelMessage.getTarget(), updateModelMessage.getMessageData(),
218 updateModelMessage.isForceInstall());
219 // Send a reply indicating the message action worked
220 sendReply(webSocket, updateModelMessage, true,
221 "updated model in engine " + updateModelMessage.getTarget().getID());
222 LOGGER.debug("updated model in engine service {}", updateModelMessage.getTarget().getID());
226 final StartEngine startEngineMessage = (StartEngine) message;
227 LOGGER.debug("starting engine {} . . .", startEngineMessage.getTarget().getID());
229 apexService.start(startEngineMessage.getTarget());
230 // Send a reply indicating the message action worked
231 sendReply(webSocket, startEngineMessage, true,
232 "started engine " + startEngineMessage.getTarget().getID());
233 LOGGER.debug("started engine {}", startEngineMessage.getTarget().getID());
237 final StopEngine stopEngineMessage = (StopEngine) message;
238 LOGGER.debug("stopping engine {} . . .", stopEngineMessage.getTarget().getID());
240 apexService.stop(stopEngineMessage.getTarget());
241 // Send a reply indicating the message action worked
242 sendReply(webSocket, stopEngineMessage, true,
243 "stopped engine " + stopEngineMessage.getTarget().getID());
244 LOGGER.debug("stopping engine {}", stopEngineMessage.getTarget().getID());
247 case START_PERIODIC_EVENTS:
248 final StartPeriodicEvents startPeriodicEventsMessage = (StartPeriodicEvents) message;
249 LOGGER.debug("starting periodic events on engine {} . . .",
250 startPeriodicEventsMessage.getTarget().getID());
251 // Start periodic events with the period specified in the message
252 final Long period = Long.parseLong(startPeriodicEventsMessage.getMessageData());
253 apexService.startPeriodicEvents(period);
254 // Send a reply indicating the message action worked
255 sendReply(webSocket, startPeriodicEventsMessage, true, "started periodic events on engine "
256 + startPeriodicEventsMessage.getTarget().getID() + " with period " + period);
257 LOGGER.debug("started periodic events on engine " + startPeriodicEventsMessage.getTarget().getID()
258 + " with period " + period);
261 case STOP_PERIODIC_EVENTS:
262 final StopPeriodicEvents stopPeriodicEventsMessage = (StopPeriodicEvents) message;
263 LOGGER.debug("stopping periodic events on engine {} . . .",
264 stopPeriodicEventsMessage.getTarget().getID());
265 // Stop periodic events
266 apexService.stopPeriodicEvents();
267 // Send a reply indicating the message action worked
268 sendReply(webSocket, stopPeriodicEventsMessage, true,
269 "stopped periodic events on engine " + stopPeriodicEventsMessage.getTarget().getID());
270 LOGGER.debug("stopped periodic events on engine " + stopPeriodicEventsMessage.getTarget().getID());
273 case GET_ENGINE_STATUS:
274 final GetEngineStatus getEngineStatusMessage = (GetEngineStatus) message;
275 LOGGER.debug("getting status for engine{} . . .", getEngineStatusMessage.getTarget().getID());
276 // Send a reply with the engine status
277 sendReply(webSocket, getEngineStatusMessage, true,
278 apexService.getStatus(getEngineStatusMessage.getTarget()));
279 LOGGER.debug("returned status for engine {}", getEngineStatusMessage.getTarget().getID());
282 case GET_ENGINE_INFO:
283 final GetEngineInfo getEngineInfo = (GetEngineInfo) message;
284 LOGGER.debug("getting runtime information for engine {} . . .", getEngineInfo.getTarget().getID());
285 // Send a reply with the engine runtime information
286 sendReply(webSocket, getEngineInfo, true, apexService.getRuntimeInfo(getEngineInfo.getTarget()));
287 LOGGER.debug("returned runtime information for engine {}", getEngineInfo.getTarget().getID());
290 throw new ApexException("RESPONSE action on received message not handled by engine");
295 } catch (final ApexException e) {
296 LOGGER.warn("apex failed to execute message", e);
297 sendReply(webSocket, message, false, e.getCascadedMessage());
298 } catch (final Exception e) {
299 LOGGER.warn("system failure executing message", e);
300 sendReply(webSocket, message, false, e.getMessage());
306 * Send the Response message to the client.
308 * @param client the client to which to send the response message
309 * @param requestMessage the message to which we are responding
310 * @param result the result indicating success or failure
311 * @param messageData the message data
313 private void sendReply(final WebSocket client, final Message requestMessage, final boolean result,
314 final String messageData) {
315 LOGGER.entry(result, messageData);
317 if (client == null || !client.isOpen()) {
318 LOGGER.debug("error sending reply {}, client has disconnected", requestMessage.getAction());
322 LOGGER.debug("sending {} to web socket {}", requestMessage.getAction(),
323 client.getRemoteSocketAddress().toString());
325 final Response responseMessage = new Response(requestMessage.getTarget(), result, requestMessage);
326 responseMessage.setMessageData(messageData);
328 final MessageHolder<Message> messageHolder = new MessageHolder<>(MessagingUtils.getHost());
329 messageHolder.addMessage(responseMessage);
330 client.send(MessagingUtils.serializeObject(messageHolder));
336 * Send the EngineServiceInfoResponse message to the client.
338 * @param client the client to which to send the response message
339 * @param requestMessage the message to which we are responding
340 * @param engineServiceKey The key of this engine service
341 * @param engineKeyCollection The keys of the engines in this engine service
342 * @param apexModelKey the apex model key
344 private void sendServiceInfoReply(final WebSocket client, final Message requestMessage,
345 final AxArtifactKey engineServiceKey, final Collection<AxArtifactKey> engineKeyCollection,
346 final AxArtifactKey apexModelKey) {
348 LOGGER.debug("sending {} to web socket {}", requestMessage.getAction(),
349 client.getRemoteSocketAddress().toString());
351 final EngineServiceInfoResponse responseMessage =
352 new EngineServiceInfoResponse(requestMessage.getTarget(), true, requestMessage);
353 responseMessage.setMessageData("engine service information");
354 responseMessage.setEngineServiceKey(engineServiceKey);
355 responseMessage.setEngineKeyArray(engineKeyCollection);
356 responseMessage.setApexModelKey(apexModelKey);
358 final MessageHolder<Message> messageHolder = new MessageHolder<>(MessagingUtils.getHost());
359 messageHolder.addMessage(responseMessage);
360 client.send(MessagingUtils.serializeObject(messageHolder));