a9b862d4123693c102ca2d611b717381b7061d76
[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      * (non-Javadoc)
115      *
116      * @see org.onap.policy.apex.core.infrastructure.messaging.MessageListener#onMessage(java.lang. String)
117      */
118     @Override
119     public void onMessage(final String messageString) {
120         throw new UnsupportedOperationException("String messages are not supported on the EngDep protocol");
121     }
122
123     /**
124      * This method gets a new message listening thread from the thread factory and starts it.
125      */
126     public void startProcessorThread() {
127         LOGGER.entry();
128         messageListenerThread = new Thread(this);
129         messageListenerThread.setDaemon(true);
130         messageListenerThread.start();
131         LOGGER.exit();
132     }
133
134     /**
135      * Stops the message listening threads.
136      */
137     public void stopProcessorThreads() {
138         LOGGER.entry();
139         stopOrderedFlag = true;
140
141         while (messageListenerThread.isAlive()) {
142             ThreadUtilities.sleep(LISTENER_STOP_WAIT_INTERVAL);
143         }
144         LOGGER.exit();
145     }
146
147     /**
148      * Runs the message listening thread. Here, the messages come in on the message queue and are processed one by one
149      */
150     @Override
151     public void run() {
152         // Take messages off the queue and forward them to the Apex engine
153         while (messageListenerThread.isAlive() && !stopOrderedFlag) {
154             try {
155                 final MessageBlock<Message> data = messageQueue.poll(QUEUE_POLL_TIMEOUT, TimeUnit.MILLISECONDS);
156                 if (data != null) {
157                     final List<Message> messages = data.getMessages();
158                     for (final Message message : messages) {
159                         handleMessage(message, data.getConnection());
160                     }
161                 }
162             } catch (final InterruptedException e) {
163                 // restore the interrupt status
164                 Thread.currentThread().interrupt();
165                 LOGGER.debug("message listener execution has been interrupted");
166                 break;
167             }
168         }
169     }
170
171     /**
172      * This method handles EngDep messages as they come in. It uses the inevitable switch statement to handle the
173      * messages.
174      *
175      * @param message the incoming EngDep message
176      * @param webSocket the web socket on which the message came in
177      */
178     private void handleMessage(final Message message, final WebSocket webSocket) {
179         LOGGER.entry(webSocket.getRemoteSocketAddress().toString());
180         if (message.getAction() == null) {
181             // This is a response message
182             return;
183         }
184
185         try {
186             LOGGER.debug("Manager action {} being applied to engine", message.getAction());
187
188             // Get and check the incoming action for validity
189             EngDepAction enDepAction = null;
190             if (message.getAction() instanceof EngDepAction) {
191                 enDepAction = (EngDepAction) message.getAction();
192             } else {
193                 throw new ApexException(message.getAction().getClass().getName()
194                                 + "action on received message invalid, action must be of type \"EnDepAction\"");
195             }
196
197             // Handle each incoming message using the inevitable switch statement for the EngDep
198             // protocol
199             switch (enDepAction) {
200                 case GET_ENGINE_SERVICE_INFO:
201                     final GetEngineServiceInfo engineServiceInformationMessage = (GetEngineServiceInfo) message;
202                     LOGGER.debug("getting engine service information for engine service " + apexService.getKey().getId()
203                                     + " . . .");
204                     // Send a reply with the engine service information
205                     sendServiceInfoReply(webSocket, engineServiceInformationMessage, apexService.getKey(),
206                                     apexService.getEngineKeys(), apexService.getApexModelKey());
207                     LOGGER.debug("returned engine service information for engine service "
208                                     + apexService.getKey().getId());
209                     break;
210
211                 case UPDATE_MODEL:
212                     final UpdateModel updateModelMessage = (UpdateModel) message;
213                     LOGGER.debug("updating model in engine {} . . .", updateModelMessage.getTarget().getId());
214                     // Update the model
215                     apexService.updateModel(updateModelMessage.getTarget(), updateModelMessage.getMessageData(),
216                                     updateModelMessage.isForceInstall());
217                     // Send a reply indicating the message action worked
218                     sendReply(webSocket, updateModelMessage, true,
219                                     "updated model in engine " + updateModelMessage.getTarget().getId());
220                     LOGGER.debug("updated model in engine service {}", updateModelMessage.getTarget().getId());
221                     break;
222
223                 case START_ENGINE:
224                     final StartEngine startEngineMessage = (StartEngine) message;
225                     LOGGER.debug("starting engine {} . . .", startEngineMessage.getTarget().getId());
226                     // Start the engine
227                     apexService.start(startEngineMessage.getTarget());
228                     // Send a reply indicating the message action worked
229                     sendReply(webSocket, startEngineMessage, true,
230                                     "started engine " + startEngineMessage.getTarget().getId());
231                     LOGGER.debug("started engine {}", startEngineMessage.getTarget().getId());
232                     break;
233
234                 case STOP_ENGINE:
235                     final StopEngine stopEngineMessage = (StopEngine) message;
236                     LOGGER.debug("stopping engine {} . . .", stopEngineMessage.getTarget().getId());
237                     // Stop the engine
238                     apexService.stop(stopEngineMessage.getTarget());
239                     // Send a reply indicating the message action worked
240                     sendReply(webSocket, stopEngineMessage, true,
241                                     "stopped engine " + stopEngineMessage.getTarget().getId());
242                     LOGGER.debug("stopping engine {}", stopEngineMessage.getTarget().getId());
243                     break;
244
245                 case START_PERIODIC_EVENTS:
246                     final StartPeriodicEvents startPeriodicEventsMessage = (StartPeriodicEvents) message;
247                     LOGGER.debug("starting periodic events on engine {} . . .",
248                                     startPeriodicEventsMessage.getTarget().getId());
249                     // Start periodic events with the period specified in the message
250                     final Long period = Long.parseLong(startPeriodicEventsMessage.getMessageData());
251                     apexService.startPeriodicEvents(period);
252                     // Send a reply indicating the message action worked
253                     String periodicStartedMessage = "started periodic events on engine "
254                                     + startPeriodicEventsMessage.getTarget().getId() + " with period " + period;
255                     sendReply(webSocket, startPeriodicEventsMessage, true, periodicStartedMessage);
256                     LOGGER.debug(periodicStartedMessage);
257                     break;
258
259                 case STOP_PERIODIC_EVENTS:
260                     final StopPeriodicEvents stopPeriodicEventsMessage = (StopPeriodicEvents) message;
261                     LOGGER.debug("stopping periodic events on engine {} . . .",
262                                     stopPeriodicEventsMessage.getTarget().getId());
263                     // Stop periodic events
264                     apexService.stopPeriodicEvents();
265                     // Send a reply indicating the message action worked
266                     sendReply(webSocket, stopPeriodicEventsMessage, true, "stopped periodic events on engine "
267                                     + stopPeriodicEventsMessage.getTarget().getId());
268                     LOGGER.debug("stopped periodic events on engine " + stopPeriodicEventsMessage.getTarget().getId());
269                     break;
270
271                 case GET_ENGINE_STATUS:
272                     final GetEngineStatus getEngineStatusMessage = (GetEngineStatus) message;
273                     LOGGER.debug("getting status for engine{} . . .", getEngineStatusMessage.getTarget().getId());
274                     // Send a reply with the engine status
275                     sendReply(webSocket, getEngineStatusMessage, true,
276                                     apexService.getStatus(getEngineStatusMessage.getTarget()));
277                     LOGGER.debug("returned status for engine {}", getEngineStatusMessage.getTarget().getId());
278                     break;
279
280                 case GET_ENGINE_INFO:
281                     final GetEngineInfo getEngineInfo = (GetEngineInfo) message;
282                     LOGGER.debug("getting runtime information for engine {} . . .", getEngineInfo.getTarget().getId());
283                     // Send a reply with the engine runtime information
284                     sendReply(webSocket, getEngineInfo, true, apexService.getRuntimeInfo(getEngineInfo.getTarget()));
285                     LOGGER.debug("returned runtime information for engine {}", getEngineInfo.getTarget().getId());
286                     break;
287                 case RESPONSE:
288                     throw new ApexException("RESPONSE action on received message not handled by engine");
289
290                 default:
291                     break;
292             }
293         } catch (final ApexException e) {
294             LOGGER.warn("apex failed to execute message", e);
295             sendReply(webSocket, message, false, e.getCascadedMessage());
296         } catch (final Exception e) {
297             LOGGER.warn("system failure executing message", e);
298             sendReply(webSocket, message, false, e.getMessage());
299         }
300         LOGGER.exit();
301     }
302
303     /**
304      * Send the Response message to the client.
305      *
306      * @param client the client to which to send the response message
307      * @param requestMessage the message to which we are responding
308      * @param result the result indicating success or failure
309      * @param messageData the message data
310      */
311     private void sendReply(final WebSocket client, final Message requestMessage, final boolean result,
312                     final String messageData) {
313         LOGGER.entry(result, messageData);
314
315         if (client == null || !client.isOpen()) {
316             LOGGER.debug("error sending reply {}, client has disconnected", requestMessage.getAction());
317             return;
318         }
319
320         String replyString = "sending " + requestMessage.getAction() + " to web socket "
321                         + client.getRemoteSocketAddress().toString();
322         LOGGER.debug(replyString);
323
324         final Response responseMessage = new Response(requestMessage.getTarget(), result, requestMessage);
325         responseMessage.setMessageData(messageData);
326
327         final MessageHolder<Message> messageHolder = new MessageHolder<>(MessagingUtils.getHost());
328         messageHolder.addMessage(responseMessage);
329         client.send(MessagingUtils.serializeObject(messageHolder));
330
331         LOGGER.exit();
332     }
333
334     /**
335      * Send the EngineServiceInfoResponse message to the client.
336      *
337      * @param client the client to which to send the response message
338      * @param requestMessage the message to which we are responding
339      * @param engineServiceKey The key of this engine service
340      * @param engineKeyCollection The keys of the engines in this engine service
341      * @param apexModelKey the apex model key
342      */
343     private void sendServiceInfoReply(final WebSocket client, final Message requestMessage,
344                     final AxArtifactKey engineServiceKey, final Collection<AxArtifactKey> engineKeyCollection,
345                     final AxArtifactKey apexModelKey) {
346         LOGGER.entry();
347         String sendingMessage = "sending " + requestMessage.getAction() + " to web socket "
348                         + client.getRemoteSocketAddress().toString();
349         LOGGER.debug(sendingMessage);
350
351         final EngineServiceInfoResponse responseMessage = new EngineServiceInfoResponse(requestMessage.getTarget(),
352                         true, requestMessage);
353         responseMessage.setMessageData("engine service information");
354         responseMessage.setEngineServiceKey(engineServiceKey);
355         responseMessage.setEngineKeyArray(engineKeyCollection);
356         responseMessage.setApexModelKey(apexModelKey);
357
358         final MessageHolder<Message> messageHolder = new MessageHolder<>(MessagingUtils.getHost());
359         messageHolder.addMessage(responseMessage);
360         client.send(MessagingUtils.serializeObject(messageHolder));
361
362         LOGGER.exit();
363     }
364 }