358069657bf21c64e10caaf12fd6207fbd2b1e38
[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.service.engine.engdep;
22
23 import com.google.common.eventbus.Subscribe;
24
25 import java.util.Collection;
26 import java.util.List;
27 import java.util.concurrent.BlockingQueue;
28 import java.util.concurrent.LinkedBlockingDeque;
29 import java.util.concurrent.TimeUnit;
30
31 import org.java_websocket.WebSocket;
32 import org.onap.policy.apex.core.infrastructure.messaging.MessageHolder;
33 import org.onap.policy.apex.core.infrastructure.messaging.MessageListener;
34 import org.onap.policy.apex.core.infrastructure.messaging.impl.ws.messageblock.MessageBlock;
35 import org.onap.policy.apex.core.infrastructure.messaging.util.MessagingUtils;
36 import org.onap.policy.apex.core.infrastructure.threading.ThreadUtilities;
37 import org.onap.policy.apex.core.protocols.Message;
38 import org.onap.policy.apex.core.protocols.engdep.EngDepAction;
39 import org.onap.policy.apex.core.protocols.engdep.messages.EngineServiceInfoResponse;
40 import org.onap.policy.apex.core.protocols.engdep.messages.GetEngineInfo;
41 import org.onap.policy.apex.core.protocols.engdep.messages.GetEngineServiceInfo;
42 import org.onap.policy.apex.core.protocols.engdep.messages.GetEngineStatus;
43 import org.onap.policy.apex.core.protocols.engdep.messages.Response;
44 import org.onap.policy.apex.core.protocols.engdep.messages.StartEngine;
45 import org.onap.policy.apex.core.protocols.engdep.messages.StartPeriodicEvents;
46 import org.onap.policy.apex.core.protocols.engdep.messages.StopEngine;
47 import org.onap.policy.apex.core.protocols.engdep.messages.StopPeriodicEvents;
48 import org.onap.policy.apex.core.protocols.engdep.messages.UpdateModel;
49 import org.onap.policy.apex.model.basicmodel.concepts.ApexException;
50 import org.onap.policy.apex.model.basicmodel.concepts.AxArtifactKey;
51 import org.onap.policy.apex.service.engine.runtime.EngineService;
52 import org.slf4j.ext.XLogger;
53 import org.slf4j.ext.XLoggerFactory;
54
55 /**
56  * The listener interface for receiving engDepMessage events. The class that is interested in processing a engDepMessage
57  * event implements this interface, and the object created with that class is registered with a component using the
58  * component's <code>addEngDepMessageListener</code> method. When the engDepMessage event occurs, that object's
59  * appropriate method is invoked.
60  * 
61  * <p>This class uses a queue to buffer incoming messages. When the listener is called, it places the incoming message
62  * on the queue. A thread runs which removes the messages from the queue and forwards them to the Apex engine.
63  *
64  * @author Sajeevan Achuthan (sajeevan.achuthan@ericsson.com)
65  */
66 public class EngDepMessageListener implements MessageListener<Message>, Runnable {
67     private static final int LISTENER_STOP_WAIT_INTERVAL = 10;
68
69     private static final XLogger LOGGER = XLoggerFactory.getXLogger(EngDepMessageListener.class);
70
71     // The timeout to wait between queue poll timeouts in milliseconds
72     private static final long QUEUE_POLL_TIMEOUT = 50;
73
74     // The Apex service itself
75     private final EngineService apexService;
76
77     // The message listener thread and stopping flag
78     private Thread messageListenerThread;
79     private boolean stopOrderedFlag = false;
80
81     // The message queue is used to hold messages prior to forwarding to Apex
82     private final BlockingQueue<MessageBlock<Message>> messageQueue = new LinkedBlockingDeque<>();
83
84     /**
85      * Instantiates a new EngDep message listener for listening for messages coming in from the Deployment client. The
86      * <code>apexService</code> is the Apex service to send the messages onto.
87      *
88      * @param apexService the Apex engine service
89      */
90     protected EngDepMessageListener(final EngineService apexService) {
91         this.apexService = apexService;
92     }
93
94     /**
95      * This method is an implementation of the message listener. It receives a message and places it on the queue for
96      * processing by the message listening thread.
97      *
98      * @param data the data
99      * @see org.onap.policy.apex.core.infrastructure.messaging.MessageListener#onMessage
100      *      (org.onap.policy.apex.core.infrastructure.messaging.impl.ws.data.Data)
101      */
102     @Subscribe
103     @Override
104     public void onMessage(final MessageBlock<Message> data) {
105         if (LOGGER.isDebugEnabled()) {
106             LOGGER.debug("message received from client application {} port {}",
107                             data.getConnection().getRemoteSocketAddress().getAddress(),
108                             data.getConnection().getRemoteSocketAddress().getPort());
109         }
110         messageQueue.add(data);
111     }
112
113     /**
114      * {@inheritDoc}.
115      */
116     @Override
117     public void onMessage(final String messageString) {
118         throw new UnsupportedOperationException("String messages are not supported on the EngDep protocol");
119     }
120
121     /**
122      * This method gets a new message listening thread from the thread factory and starts it.
123      */
124     public void startProcessorThread() {
125         LOGGER.entry();
126         messageListenerThread = new Thread(this);
127         messageListenerThread.setDaemon(true);
128         messageListenerThread.start();
129         LOGGER.exit();
130     }
131
132     /**
133      * Stops the message listening threads.
134      */
135     public void stopProcessorThreads() {
136         LOGGER.entry();
137         stopOrderedFlag = true;
138
139         while (messageListenerThread.isAlive()) {
140             ThreadUtilities.sleep(LISTENER_STOP_WAIT_INTERVAL);
141         }
142         LOGGER.exit();
143     }
144
145     /**
146      * Runs the message listening thread. Here, the messages come in on the message queue and are processed one by one
147      */
148     @Override
149     public void run() {
150         // Take messages off the queue and forward them to the Apex engine
151         while (messageListenerThread.isAlive() && !stopOrderedFlag) {
152             pollAndHandleMessage();
153         }
154     }
155
156     /**
157      * Poll the queue for a message and handle that message.
158      */
159     private void pollAndHandleMessage() {
160         try {
161             final MessageBlock<Message> data = messageQueue.poll(QUEUE_POLL_TIMEOUT, TimeUnit.MILLISECONDS);
162             if (data != null) {
163                 final List<Message> messages = data.getMessages();
164                 for (final Message message : messages) {
165                     handleMessage(message, data.getConnection());
166                 }
167             }
168         } catch (final InterruptedException e) {
169             // restore the interrupt status
170             Thread.currentThread().interrupt();
171             LOGGER.debug("message listener execution has been interrupted");
172         }
173     }
174
175     /**
176      * This method handles EngDep messages as they come in. It uses the inevitable switch statement to handle the
177      * messages.
178      *
179      * @param message the incoming EngDep message
180      * @param webSocket the web socket on which the message came in
181      */
182     private void handleMessage(final Message message, final WebSocket webSocket) {
183         LOGGER.entry(webSocket.getRemoteSocketAddress().toString());
184         if (message.getAction() == null) {
185             // This is a response message
186             return;
187         }
188
189         try {
190             LOGGER.debug("Manager action {} being applied to engine", message.getAction());
191
192             // Get and check the incoming action for validity
193             EngDepAction enDepAction = null;
194             if (message.getAction() instanceof EngDepAction) {
195                 enDepAction = (EngDepAction) message.getAction();
196             } else {
197                 throw new ApexException(message.getAction().getClass().getName()
198                                 + "action on received message invalid, action must be of type \"EnDepAction\"");
199             }
200
201             handleIncomingMessages(message, webSocket, enDepAction);
202         } catch (final ApexException e) {
203             LOGGER.warn("apex failed to execute message", e);
204             sendReply(webSocket, message, false, e.getCascadedMessage());
205         } catch (final Exception e) {
206             LOGGER.warn("system failure executing message", e);
207             sendReply(webSocket, message, false, e.getMessage());
208         }
209         LOGGER.exit();
210     }
211
212     /**
213      * Handle incoming EngDep messages.
214      * 
215      * @param message the incoming message
216      * @param webSocket the web socket the message came in on
217      * @param enDepAction the action from the message
218      * @throws ApexException on message handling errors
219      */
220     private void handleIncomingMessages(final Message message, final WebSocket webSocket, EngDepAction enDepAction)
221                     throws ApexException {
222         // Handle each incoming message using the inevitable switch statement for the EngDep
223         // protocol
224         switch (enDepAction) {
225             case GET_ENGINE_SERVICE_INFO:
226                 handleGetEngineServiceInfoMessage(message, webSocket);
227                 break;
228
229             case UPDATE_MODEL:
230                 handleUpdateModelMessage(message, webSocket);
231                 break;
232
233             case START_ENGINE:
234                 handleStartEngineMessage(message, webSocket);
235                 break;
236
237             case STOP_ENGINE:
238                 handleStopEngineMessage(message, webSocket);
239                 break;
240
241             case START_PERIODIC_EVENTS:
242                 handleStartPeriodicEventsMessage(message, webSocket);
243                 break;
244
245             case STOP_PERIODIC_EVENTS:
246                 handleStopPeriodicEventsMessage(message, webSocket);
247                 break;
248
249             case GET_ENGINE_STATUS:
250                 handleEngineStatusMessage(message, webSocket);
251                 break;
252
253             case GET_ENGINE_INFO:
254                 handleEngineInfoMessage(message, webSocket);
255                 break;
256                 
257             default:
258                 throw new ApexException("action " + enDepAction + " on received message not handled by engine");
259         }
260     }
261
262     /**
263      * Handle the get engine service information message.
264      * 
265      * @param message the message
266      * @param webSocket the web socket that the message came on
267      * @throws ApexException on message handling exceptions
268      */
269     private void handleGetEngineServiceInfoMessage(final Message message, final WebSocket webSocket) {
270         final GetEngineServiceInfo engineServiceInformationMessage = (GetEngineServiceInfo) message;
271         LOGGER.debug("getting engine service information for engine service " + apexService.getKey().getId()
272                         + " . . .");
273         // Send a reply with the engine service information
274         sendServiceInfoReply(webSocket, engineServiceInformationMessage, apexService.getKey(),
275                         apexService.getEngineKeys(), apexService.getApexModelKey());
276         LOGGER.debug("returned engine service information for engine service "
277                         + apexService.getKey().getId());
278     }
279
280     /**
281      * Handle the update model message.
282      * 
283      * @param message the message
284      * @param webSocket the web socket that the message came on
285      * @throws ApexException on message handling exceptions
286      */
287     private void handleUpdateModelMessage(final Message message, final WebSocket webSocket) throws ApexException {
288         final UpdateModel updateModelMessage = (UpdateModel) message;
289         LOGGER.debug("updating model in engine {} . . .", updateModelMessage.getTarget().getId());
290         // Update the model
291         apexService.updateModel(updateModelMessage.getTarget(), updateModelMessage.getMessageData(),
292                         updateModelMessage.isForceInstall());
293         // Send a reply indicating the message action worked
294         sendReply(webSocket, updateModelMessage, true,
295                         "updated model in engine " + updateModelMessage.getTarget().getId());
296         LOGGER.debug("updated model in engine service {}", updateModelMessage.getTarget().getId());
297     }
298
299     /**
300      * Handle the start engine message.
301      * 
302      * @param message the message
303      * @param webSocket the web socket that the message came on
304      * @throws ApexException on message handling exceptions
305      */
306     private void handleStartEngineMessage(final Message message, final WebSocket webSocket) throws ApexException {
307         final StartEngine startEngineMessage = (StartEngine) message;
308         LOGGER.debug("starting engine {} . . .", startEngineMessage.getTarget().getId());
309         // Start the engine
310         apexService.start(startEngineMessage.getTarget());
311         // Send a reply indicating the message action worked
312         sendReply(webSocket, startEngineMessage, true,
313                         "started engine " + startEngineMessage.getTarget().getId());
314         LOGGER.debug("started engine {}", startEngineMessage.getTarget().getId());
315     }
316
317     /**
318      * Handle the stop engine message.
319      * 
320      * @param message the message
321      * @param webSocket the web socket that the message came on
322      * @throws ApexException on message handling exceptions
323      */
324     private void handleStopEngineMessage(final Message message, final WebSocket webSocket) throws ApexException {
325         final StopEngine stopEngineMessage = (StopEngine) message;
326         LOGGER.debug("stopping engine {} . . .", stopEngineMessage.getTarget().getId());
327         // Stop the engine
328         apexService.stop(stopEngineMessage.getTarget());
329         // Send a reply indicating the message action worked
330         sendReply(webSocket, stopEngineMessage, true,
331                         "stopped engine " + stopEngineMessage.getTarget().getId());
332         LOGGER.debug("stopping engine {}", stopEngineMessage.getTarget().getId());
333     }
334
335     /**
336      * Handle the start periodic events message.
337      * 
338      * @param message the message
339      * @param webSocket the web socket that the message came on
340      * @throws ApexException on message handling exceptions
341      */
342     private void handleStartPeriodicEventsMessage(final Message message, final WebSocket webSocket)
343                     throws ApexException {
344         final StartPeriodicEvents startPeriodicEventsMessage = (StartPeriodicEvents) message;
345         LOGGER.debug("starting periodic events on engine {} . . .",
346                         startPeriodicEventsMessage.getTarget().getId());
347         // Start periodic events with the period specified in the message
348         final Long period = Long.parseLong(startPeriodicEventsMessage.getMessageData());
349         apexService.startPeriodicEvents(period);
350         // Send a reply indicating the message action worked
351         String periodicStartedMessage = "started periodic events on engine "
352                         + startPeriodicEventsMessage.getTarget().getId() + " with period " + period;
353         sendReply(webSocket, startPeriodicEventsMessage, true, periodicStartedMessage);
354         LOGGER.debug(periodicStartedMessage);
355     }
356
357     /**
358      * Handle the stop periodic events message.
359      * 
360      * @param message the message
361      * @param webSocket the web socket that the message came on
362      * @throws ApexException on message handling exceptions
363      */
364     private void handleStopPeriodicEventsMessage(final Message message, final WebSocket webSocket)
365                     throws ApexException {
366         final StopPeriodicEvents stopPeriodicEventsMessage = (StopPeriodicEvents) message;
367         LOGGER.debug("stopping periodic events on engine {} . . .",
368                         stopPeriodicEventsMessage.getTarget().getId());
369         // Stop periodic events
370         apexService.stopPeriodicEvents();
371         // Send a reply indicating the message action worked
372         sendReply(webSocket, stopPeriodicEventsMessage, true, "stopped periodic events on engine "
373                         + stopPeriodicEventsMessage.getTarget().getId());
374         LOGGER.debug("stopped periodic events on engine " + stopPeriodicEventsMessage.getTarget().getId());
375     }
376
377     /**
378      * Handle the engine status message.
379      * 
380      * @param message the message
381      * @param webSocket the web socket that the message came on
382      * @throws ApexException on message handling exceptions
383      */
384     private void handleEngineStatusMessage(final Message message, final WebSocket webSocket) throws ApexException {
385         final GetEngineStatus getEngineStatusMessage = (GetEngineStatus) message;
386         LOGGER.debug("getting status for engine{} . . .", getEngineStatusMessage.getTarget().getId());
387         // Send a reply with the engine status
388         sendReply(webSocket, getEngineStatusMessage, true,
389                         apexService.getStatus(getEngineStatusMessage.getTarget()));
390         LOGGER.debug("returned status for engine {}", getEngineStatusMessage.getTarget().getId());
391     }
392
393     /**
394      * Handle the engine information message.
395      * 
396      * @param message the message
397      * @param webSocket the web socket that the message came on
398      * @throws ApexException on message handling exceptions
399      */
400     private void handleEngineInfoMessage(final Message message, final WebSocket webSocket) throws ApexException {
401         final GetEngineInfo getEngineInfo = (GetEngineInfo) message;
402         LOGGER.debug("getting runtime information for engine {} . . .", getEngineInfo.getTarget().getId());
403         // Send a reply with the engine runtime information
404         sendReply(webSocket, getEngineInfo, true, apexService.getRuntimeInfo(getEngineInfo.getTarget()));
405         LOGGER.debug("returned runtime information for engine {}", getEngineInfo.getTarget().getId());
406     }
407
408     /**
409      * Send the Response message to the client.
410      *
411      * @param client the client to which to send the response message
412      * @param requestMessage the message to which we are responding
413      * @param result the result indicating success or failure
414      * @param messageData the message data
415      */
416     private void sendReply(final WebSocket client, final Message requestMessage, final boolean result,
417                     final String messageData) {
418         LOGGER.entry(result, messageData);
419
420         if (client == null || !client.isOpen()) {
421             LOGGER.debug("error sending reply {}, client has disconnected", requestMessage.getAction());
422             return;
423         }
424
425         String replyString = "sending " + requestMessage.getAction() + " to web socket "
426                         + client.getRemoteSocketAddress().toString();
427         LOGGER.debug(replyString);
428
429         final Response responseMessage = new Response(requestMessage.getTarget(), result, requestMessage);
430         responseMessage.setMessageData(messageData);
431
432         final MessageHolder<Message> messageHolder = new MessageHolder<>(MessagingUtils.getHost());
433         messageHolder.addMessage(responseMessage);
434         client.send(MessagingUtils.serializeObject(messageHolder));
435
436         LOGGER.exit();
437     }
438
439     /**
440      * Send the EngineServiceInfoResponse message to the client.
441      *
442      * @param client the client to which to send the response message
443      * @param requestMessage the message to which we are responding
444      * @param engineServiceKey The key of this engine service
445      * @param engineKeyCollection The keys of the engines in this engine service
446      * @param apexModelKey the apex model key
447      */
448     private void sendServiceInfoReply(final WebSocket client, final Message requestMessage,
449                     final AxArtifactKey engineServiceKey, final Collection<AxArtifactKey> engineKeyCollection,
450                     final AxArtifactKey apexModelKey) {
451         LOGGER.entry();
452         String sendingMessage = "sending " + requestMessage.getAction() + " to web socket "
453                         + client.getRemoteSocketAddress().toString();
454         LOGGER.debug(sendingMessage);
455
456         final EngineServiceInfoResponse responseMessage = new EngineServiceInfoResponse(requestMessage.getTarget(),
457                         true, requestMessage);
458         responseMessage.setMessageData("engine service information");
459         responseMessage.setEngineServiceKey(engineServiceKey);
460         responseMessage.setEngineKeyArray(engineKeyCollection);
461         responseMessage.setApexModelKey(apexModelKey);
462
463         final MessageHolder<Message> messageHolder = new MessageHolder<>(MessagingUtils.getHost());
464         messageHolder.addMessage(responseMessage);
465         client.send(MessagingUtils.serializeObject(messageHolder));
466
467         LOGGER.exit();
468     }
469 }