dbc2c4ea63024998078fbb68147d14d5327e0261
[policy/clamp.git] /
1 /*-
2  * ============LICENSE_START=======================================================
3  *  Copyright (C) 2021 Nordix Foundation.
4  *  Modifications Copyright (C) 2021 AT&T Intellectual Property. All rights reserved.
5  * ================================================================================
6  * Licensed under the Apache License, Version 2.0 (the "License");
7  * you may not use this file except in compliance with the License.
8  * You may obtain a copy of the License at
9  *
10  *      http://www.apache.org/licenses/LICENSE-2.0
11  *
12  * Unless required by applicable law or agreed to in writing, software
13  * distributed under the License is distributed on an "AS IS" BASIS,
14  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  * See the License for the specific language governing permissions and
16  * limitations under the License.
17  *
18  * SPDX-License-Identifier: Apache-2.0
19  * ============LICENSE_END=========================================================
20  */
21
22 package org.onap.policy.clamp.controlloop.runtime.supervision;
23
24 import java.util.List;
25 import java.util.Map;
26 import java.util.Set;
27 import java.util.UUID;
28 import javax.ws.rs.core.Response;
29 import lombok.AllArgsConstructor;
30 import org.apache.commons.collections4.CollectionUtils;
31 import org.onap.policy.clamp.controlloop.common.exception.ControlLoopException;
32 import org.onap.policy.clamp.controlloop.models.controlloop.concepts.ControlLoop;
33 import org.onap.policy.clamp.controlloop.models.controlloop.concepts.ControlLoopElementAck;
34 import org.onap.policy.clamp.controlloop.models.controlloop.concepts.ControlLoopInfo;
35 import org.onap.policy.clamp.controlloop.models.controlloop.concepts.ControlLoopState;
36 import org.onap.policy.clamp.controlloop.models.controlloop.concepts.Participant;
37 import org.onap.policy.clamp.controlloop.models.controlloop.concepts.ParticipantHealthStatus;
38 import org.onap.policy.clamp.controlloop.models.controlloop.concepts.ParticipantState;
39 import org.onap.policy.clamp.controlloop.models.controlloop.persistence.provider.ControlLoopProvider;
40 import org.onap.policy.clamp.controlloop.models.controlloop.persistence.provider.ParticipantProvider;
41 import org.onap.policy.clamp.controlloop.models.messages.dmaap.participant.ControlLoopAck;
42 import org.onap.policy.clamp.controlloop.models.messages.dmaap.participant.ParticipantDeregister;
43 import org.onap.policy.clamp.controlloop.models.messages.dmaap.participant.ParticipantRegister;
44 import org.onap.policy.clamp.controlloop.models.messages.dmaap.participant.ParticipantStatus;
45 import org.onap.policy.clamp.controlloop.models.messages.dmaap.participant.ParticipantUpdate;
46 import org.onap.policy.clamp.controlloop.models.messages.dmaap.participant.ParticipantUpdateAck;
47 import org.onap.policy.clamp.controlloop.runtime.monitoring.MonitoringProvider;
48 import org.onap.policy.clamp.controlloop.runtime.supervision.comm.ControlLoopStateChangePublisher;
49 import org.onap.policy.clamp.controlloop.runtime.supervision.comm.ControlLoopUpdatePublisher;
50 import org.onap.policy.clamp.controlloop.runtime.supervision.comm.ParticipantDeregisterAckPublisher;
51 import org.onap.policy.clamp.controlloop.runtime.supervision.comm.ParticipantRegisterAckPublisher;
52 import org.onap.policy.clamp.controlloop.runtime.supervision.comm.ParticipantUpdatePublisher;
53 import org.onap.policy.models.base.PfModelException;
54 import org.onap.policy.models.tosca.authorative.concepts.ToscaConceptIdentifier;
55 import org.slf4j.Logger;
56 import org.slf4j.LoggerFactory;
57 import org.springframework.stereotype.Component;
58
59 /**
60  * This class handles supervision of control loop instances, so only one object of this type should be built at a time.
61  *
62  * <p/>
63  * It is effectively a singleton that is started at system start.
64  */
65 @Component
66 @AllArgsConstructor
67 public class SupervisionHandler {
68     private static final Logger LOGGER = LoggerFactory.getLogger(SupervisionHandler.class);
69
70     private static final String CONTROL_LOOP_CANNOT_TRANSITION_FROM_STATE = "Control loop can't transition from state ";
71     private static final String CONTROL_LOOP_IS_ALREADY_IN_STATE = "Control loop is already in state ";
72     private static final String TO_STATE = " to state ";
73     private static final String AND_TRANSITIONING_TO_STATE = " and transitioning to state ";
74
75     private final ControlLoopProvider controlLoopProvider;
76     private final ParticipantProvider participantProvider;
77     private final MonitoringProvider monitoringProvider;
78
79     // Publishers for participant communication
80     private final ControlLoopUpdatePublisher controlLoopUpdatePublisher;
81     private final ControlLoopStateChangePublisher controlLoopStateChangePublisher;
82     private final ParticipantRegisterAckPublisher participantRegisterAckPublisher;
83     private final ParticipantDeregisterAckPublisher participantDeregisterAckPublisher;
84     private final ParticipantUpdatePublisher participantUpdatePublisher;
85
86     /**
87      * Supervision trigger called when a command is issued on control loops.
88      *
89      * <p/>
90      * Causes supervision to start or continue supervision on the control loops in question.
91      *
92      * @param controlLoopIdentifierList the control loops for which the supervision command has been issued
93      * @throws ControlLoopException on supervision triggering exceptions
94      */
95     public void triggerControlLoopSupervision(List<ToscaConceptIdentifier> controlLoopIdentifierList)
96             throws ControlLoopException {
97
98         LOGGER.debug("triggering control loop supervision on control loops {}", controlLoopIdentifierList);
99
100         if (CollectionUtils.isEmpty(controlLoopIdentifierList)) {
101             // This is just to force throwing of the exception in certain circumstances.
102             exceptionOccured(Response.Status.NOT_ACCEPTABLE, "The list of control loops for supervision is empty");
103         }
104
105         for (ToscaConceptIdentifier controlLoopId : controlLoopIdentifierList) {
106             try {
107                 var controlLoop = controlLoopProvider.getControlLoop(controlLoopId);
108
109                 superviseControlLoop(controlLoop);
110
111                 controlLoopProvider.updateControlLoop(controlLoop);
112             } catch (PfModelException pfme) {
113                 throw new ControlLoopException(pfme.getErrorResponse().getResponseCode(), pfme.getMessage(), pfme);
114             }
115         }
116     }
117
118     /**
119      * Handle a ParticipantStatus message from a participant.
120      *
121      * @param participantStatusMessage the ParticipantStatus message received from a participant
122      */
123     @MessageIntercept
124     public void handleParticipantMessage(ParticipantStatus participantStatusMessage) {
125         LOGGER.debug("Participant Status received {}", participantStatusMessage);
126         try {
127             superviseParticipant(participantStatusMessage);
128         } catch (PfModelException | ControlLoopException svExc) {
129             LOGGER.warn("error supervising participant {}", participantStatusMessage.getParticipantId(), svExc);
130             return;
131         }
132
133         try {
134             superviseControlLoops(participantStatusMessage);
135         } catch (PfModelException | ControlLoopException svExc) {
136             LOGGER.warn("error supervising participant {}", participantStatusMessage.getParticipantId(), svExc);
137         }
138     }
139
140     /**
141      * Handle a ParticipantRegister message from a participant.
142      *
143      * @param participantRegisterMessage the ParticipantRegister message received from a participant
144      */
145     @MessageIntercept
146     public void handleParticipantMessage(ParticipantRegister participantRegisterMessage) {
147         LOGGER.debug("Participant Register received {}", participantRegisterMessage);
148
149         participantRegisterAckPublisher.send(participantRegisterMessage.getMessageId(),
150                 participantRegisterMessage.getParticipantId(), participantRegisterMessage.getParticipantType());
151
152         participantUpdatePublisher.send(participantRegisterMessage.getParticipantId(),
153                 participantRegisterMessage.getParticipantType(), true);
154     }
155
156     /**
157      * Handle a ParticipantDeregister message from a participant.
158      *
159      * @param participantDeregisterMessage the ParticipantDeregister message received from a participant
160      */
161     @MessageIntercept
162     public void handleParticipantMessage(ParticipantDeregister participantDeregisterMessage) {
163         LOGGER.debug("Participant Deregister received {}", participantDeregisterMessage);
164         try {
165             var participantList =
166                 participantProvider.getParticipants(participantDeregisterMessage.getParticipantId().getName(),
167                     participantDeregisterMessage.getParticipantId().getVersion());
168
169             if (participantList != null) {
170                 for (Participant participant : participantList) {
171                     participant.setParticipantState(ParticipantState.TERMINATED);
172                     participant.setHealthStatus(ParticipantHealthStatus.OFF_LINE);
173                 }
174                 participantProvider.updateParticipants(participantList);
175             }
176         } catch (PfModelException pfme) {
177             LOGGER.warn("Model exception occured {}", participantDeregisterMessage.getParticipantId());
178         }
179
180         participantDeregisterAckPublisher.send(participantDeregisterMessage.getMessageId());
181     }
182
183     /**
184      * Handle a ParticipantUpdateAck message from a participant.
185      *
186      * @param participantUpdateAckMessage the ParticipantUpdateAck message received from a participant
187      */
188     @MessageIntercept
189     public void handleParticipantMessage(ParticipantUpdateAck participantUpdateAckMessage) {
190         LOGGER.debug("Participant Update Ack received {}", participantUpdateAckMessage);
191         try {
192             var participantList =
193                 participantProvider.getParticipants(participantUpdateAckMessage.getParticipantId().getName(),
194                     participantUpdateAckMessage.getParticipantId().getVersion());
195
196             if (participantList != null) {
197                 for (Participant participant : participantList) {
198                     participant.setParticipantState(participantUpdateAckMessage.getState());
199                 }
200                 participantProvider.updateParticipants(participantList);
201             } else {
202                 LOGGER.warn("Participant not found in database {}", participantUpdateAckMessage.getParticipantId());
203             }
204         } catch (PfModelException pfme) {
205             LOGGER.warn("Model exception occured {}", participantUpdateAckMessage.getParticipantId());
206         }
207     }
208
209     /**
210      * Send commissioning update message to dmaap.
211      *
212      * @param participantUpdateMessage the ParticipantUpdate message to send
213      */
214     public void handleSendCommissionMessage(ParticipantUpdate participantUpdateMessage) {
215         LOGGER.debug("Participant update message being sent {}", participantUpdateMessage);
216
217         participantUpdatePublisher.send(participantUpdateMessage.getParticipantId(),
218             participantUpdateMessage.getParticipantType(), true);
219     }
220
221     /**
222      * Send decommissioning update message to dmaap.
223      *
224      * @param participantUpdateMessage the ParticipantUpdate message to send
225      */
226     public void handleSendDeCommissionMessage(ParticipantUpdate participantUpdateMessage) {
227         LOGGER.debug("Participant update message being sent {}", participantUpdateMessage);
228
229         participantUpdatePublisher.send(participantUpdateMessage.getParticipantId(),
230             participantUpdateMessage.getParticipantType(), false);
231     }
232
233     /**
234      * Handle a ControlLoop update acknowledge message from a participant.
235      *
236      * @param controlLoopAckMessage the ControlLoopAck message received from a participant
237      */
238     @MessageIntercept
239     public void handleControlLoopUpdateAckMessage(ControlLoopAck controlLoopAckMessage) {
240         LOGGER.debug("ControlLoop Update Ack message received {}", controlLoopAckMessage);
241         setClElementStateInDb(controlLoopAckMessage);
242     }
243
244     /**
245      * Handle a ControlLoop statechange acknowledge message from a participant.
246      *
247      * @param controlLoopAckMessage the ControlLoopAck message received from a participant
248      */
249     @MessageIntercept
250     public void handleControlLoopStateChangeAckMessage(ControlLoopAck controlLoopAckMessage) {
251         LOGGER.debug("ControlLoop StateChange Ack message received {}", controlLoopAckMessage);
252         setClElementStateInDb(controlLoopAckMessage);
253     }
254
255     private void setClElementStateInDb(ControlLoopAck controlLoopAckMessage) {
256         if (controlLoopAckMessage.getControlLoopResultMap() != null) {
257             try {
258                 var controlLoop = controlLoopProvider.getControlLoop(controlLoopAckMessage.getControlLoopId());
259                 if (controlLoop != null) {
260                     var updated = updateState(controlLoop, controlLoopAckMessage
261                             .getControlLoopResultMap().entrySet());
262                     if (updated) {
263                         controlLoopProvider.updateControlLoop(controlLoop);
264                     }
265                 } else {
266                     LOGGER.warn("ControlLoop not found in database {}", controlLoopAckMessage.getControlLoopId());
267                 }
268             } catch (PfModelException pfme) {
269                 LOGGER.warn("Model exception occured {}", controlLoopAckMessage.getControlLoopId());
270             }
271         }
272     }
273
274     private boolean updateState(ControlLoop controlLoop, Set<Map.Entry<UUID, ControlLoopElementAck>>
275             controlLoopResultSet) {
276         var updated = false;
277         for (var clElementAck : controlLoopResultSet) {
278             var element = controlLoop.getElements().get(clElementAck.getKey());
279             if (element != null) {
280                 element.setState(clElementAck.getValue().getState());
281                 updated = true;
282             }
283         }
284         return updated;
285     }
286
287     /**
288      * Supervise a control loop, performing whatever actions need to be performed on the control loop.
289      *
290      * @param controlLoop the control loop to supervises
291      * @throws ControlLoopException on supervision errors
292      */
293     private void superviseControlLoop(ControlLoop controlLoop) throws ControlLoopException {
294         switch (controlLoop.getOrderedState()) {
295             case UNINITIALISED:
296                 superviseControlLoopUninitialization(controlLoop);
297                 break;
298
299             case PASSIVE:
300                 superviseControlLoopPassivation(controlLoop);
301                 break;
302
303             case RUNNING:
304                 superviseControlLoopActivation(controlLoop);
305                 break;
306
307             default:
308                 exceptionOccured(Response.Status.NOT_ACCEPTABLE,
309                         "A control loop cannot be commanded to go into state " + controlLoop.getOrderedState().name());
310         }
311     }
312
313     /**
314      * Supervise a control loop uninitialisation, performing whatever actions need to be performed on the control loop,
315      * control loop ordered state is UNINITIALIZED.
316      *
317      * @param controlLoop the control loop to supervises
318      * @throws ControlLoopException on supervision errors
319      */
320     private void superviseControlLoopUninitialization(ControlLoop controlLoop) throws ControlLoopException {
321         switch (controlLoop.getState()) {
322             case UNINITIALISED:
323                 exceptionOccured(Response.Status.NOT_ACCEPTABLE,
324                         CONTROL_LOOP_IS_ALREADY_IN_STATE + controlLoop.getState().name());
325                 break;
326
327             case UNINITIALISED2PASSIVE:
328             case PASSIVE:
329                 controlLoop.setState(ControlLoopState.PASSIVE2UNINITIALISED);
330                 controlLoopStateChangePublisher.send(controlLoop);
331                 break;
332
333             case PASSIVE2UNINITIALISED:
334                 exceptionOccured(Response.Status.NOT_ACCEPTABLE, CONTROL_LOOP_IS_ALREADY_IN_STATE
335                         + controlLoop.getState().name() + AND_TRANSITIONING_TO_STATE + controlLoop.getOrderedState());
336                 break;
337
338             default:
339                 exceptionOccured(Response.Status.NOT_ACCEPTABLE, CONTROL_LOOP_CANNOT_TRANSITION_FROM_STATE
340                         + controlLoop.getState().name() + TO_STATE + controlLoop.getOrderedState());
341                 break;
342         }
343     }
344
345     private void superviseControlLoopPassivation(ControlLoop controlLoop)
346             throws ControlLoopException {
347         switch (controlLoop.getState()) {
348             case PASSIVE:
349                 exceptionOccured(Response.Status.NOT_ACCEPTABLE,
350                         CONTROL_LOOP_IS_ALREADY_IN_STATE + controlLoop.getState().name());
351                 break;
352             case UNINITIALISED:
353                 controlLoop.setState(ControlLoopState.UNINITIALISED2PASSIVE);
354                 controlLoopUpdatePublisher.send(controlLoop);
355                 break;
356
357             case UNINITIALISED2PASSIVE:
358             case RUNNING2PASSIVE:
359                 exceptionOccured(Response.Status.NOT_ACCEPTABLE, CONTROL_LOOP_IS_ALREADY_IN_STATE
360                         + controlLoop.getState().name() + AND_TRANSITIONING_TO_STATE + controlLoop.getOrderedState());
361                 break;
362
363             case RUNNING:
364                 controlLoop.setState(ControlLoopState.RUNNING2PASSIVE);
365                 controlLoopStateChangePublisher.send(controlLoop);
366                 break;
367
368             default:
369                 exceptionOccured(Response.Status.NOT_ACCEPTABLE, CONTROL_LOOP_CANNOT_TRANSITION_FROM_STATE
370                         + controlLoop.getState().name() + TO_STATE + controlLoop.getOrderedState());
371                 break;
372         }
373     }
374
375     private void superviseControlLoopActivation(ControlLoop controlLoop) throws ControlLoopException {
376         switch (controlLoop.getState()) {
377             case RUNNING:
378                 exceptionOccured(Response.Status.NOT_ACCEPTABLE,
379                         CONTROL_LOOP_IS_ALREADY_IN_STATE + controlLoop.getState().name());
380                 break;
381
382             case PASSIVE2RUNNING:
383                 exceptionOccured(Response.Status.NOT_ACCEPTABLE, CONTROL_LOOP_IS_ALREADY_IN_STATE
384                         + controlLoop.getState().name() + AND_TRANSITIONING_TO_STATE + controlLoop.getOrderedState());
385                 break;
386
387             case PASSIVE:
388                 controlLoop.setState(ControlLoopState.PASSIVE2RUNNING);
389                 controlLoopStateChangePublisher.send(controlLoop);
390                 break;
391
392             default:
393                 exceptionOccured(Response.Status.NOT_ACCEPTABLE, CONTROL_LOOP_CANNOT_TRANSITION_FROM_STATE
394                         + controlLoop.getState().name() + TO_STATE + controlLoop.getOrderedState());
395                 break;
396         }
397     }
398
399     private void superviseParticipant(ParticipantStatus participantStatusMessage)
400             throws PfModelException, ControlLoopException {
401         if (participantStatusMessage.getParticipantId() == null) {
402             exceptionOccured(Response.Status.NOT_FOUND, "Participant ID on PARTICIPANT_STATUS message is null");
403         }
404
405         List<Participant> participantList =
406                 participantProvider.getParticipants(participantStatusMessage.getParticipantId().getName(),
407                         participantStatusMessage.getParticipantId().getVersion());
408
409         if (CollectionUtils.isEmpty(participantList)) {
410             var participant = new Participant();
411             participant.setName(participantStatusMessage.getParticipantId().getName());
412             participant.setVersion(participantStatusMessage.getParticipantId().getVersion());
413             participant.setDefinition(new ToscaConceptIdentifier("unknown", "0.0.0"));
414             participant.setParticipantState(participantStatusMessage.getState());
415             participant.setHealthStatus(participantStatusMessage.getHealthStatus());
416
417             participantList.add(participant);
418             participantProvider.createParticipants(participantList);
419         } else {
420             for (Participant participant : participantList) {
421                 participant.setParticipantState(participantStatusMessage.getState());
422                 participant.setHealthStatus(participantStatusMessage.getHealthStatus());
423             }
424             participantProvider.updateParticipants(participantList);
425         }
426
427         monitoringProvider.createParticipantStatistics(List.of(participantStatusMessage.getParticipantStatistics()));
428     }
429
430     private void superviseControlLoops(ParticipantStatus participantStatusMessage)
431             throws PfModelException, ControlLoopException {
432         if (participantStatusMessage.getControlLoopInfoList() != null) {
433             for (ControlLoopInfo clEntry : participantStatusMessage.getControlLoopInfoList()) {
434                 var dbControlLoop =
435                         controlLoopProvider.getControlLoop(new ToscaConceptIdentifier(clEntry.getControlLoopId()));
436                 if (dbControlLoop == null) {
437                     exceptionOccured(Response.Status.NOT_FOUND,
438                             "PARTICIPANT_STATUS control loop not found in database: " + clEntry.getControlLoopId());
439                 }
440                 dbControlLoop.setState(clEntry.getState());
441                 monitoringProvider.createClElementStatistics(
442                         clEntry.getControlLoopStatistics().getClElementStatisticsList().getClElementStatistics());
443             }
444         }
445     }
446
447     private void exceptionOccured(Response.Status status, String reason) throws ControlLoopException {
448         throw new ControlLoopException(status, reason);
449     }
450 }