8bdf91824d71e11dad3e90431b724b26d1a1e913
[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.participant.intermediary.handler;
23
24 import java.util.ArrayList;
25 import java.util.LinkedHashMap;
26 import java.util.List;
27 import java.util.Map;
28 import java.util.UUID;
29 import java.util.stream.Collectors;
30 import lombok.Getter;
31 import org.onap.policy.clamp.controlloop.models.controlloop.concepts.ClElementStatistics;
32 import org.onap.policy.clamp.controlloop.models.controlloop.concepts.ControlLoop;
33 import org.onap.policy.clamp.controlloop.models.controlloop.concepts.ControlLoopElement;
34 import org.onap.policy.clamp.controlloop.models.controlloop.concepts.ControlLoopElementAck;
35 import org.onap.policy.clamp.controlloop.models.controlloop.concepts.ControlLoopElementDefinition;
36 import org.onap.policy.clamp.controlloop.models.controlloop.concepts.ControlLoopOrderedState;
37 import org.onap.policy.clamp.controlloop.models.controlloop.concepts.ControlLoopState;
38 import org.onap.policy.clamp.controlloop.models.controlloop.concepts.ControlLoops;
39 import org.onap.policy.clamp.controlloop.models.controlloop.concepts.ParticipantUpdates;
40 import org.onap.policy.clamp.controlloop.models.messages.dmaap.participant.ControlLoopAck;
41 import org.onap.policy.clamp.controlloop.models.messages.dmaap.participant.ControlLoopStateChange;
42 import org.onap.policy.clamp.controlloop.models.messages.dmaap.participant.ControlLoopUpdate;
43 import org.onap.policy.clamp.controlloop.models.messages.dmaap.participant.ParticipantMessageType;
44 import org.onap.policy.clamp.controlloop.participant.intermediary.api.ControlLoopElementListener;
45 import org.onap.policy.clamp.controlloop.participant.intermediary.comm.ParticipantMessagePublisher;
46 import org.onap.policy.clamp.controlloop.participant.intermediary.parameters.ParticipantParameters;
47 import org.onap.policy.models.base.PfModelException;
48 import org.onap.policy.models.tosca.authorative.concepts.ToscaConceptIdentifier;
49 import org.onap.policy.models.tosca.authorative.concepts.ToscaNodeTemplate;
50 import org.slf4j.Logger;
51 import org.slf4j.LoggerFactory;
52 import org.springframework.stereotype.Component;
53
54 /*
55  * This class is responsible for managing the state of all control loops in the participant.
56  */
57 @Component
58 public class ControlLoopHandler {
59     private static final Logger LOGGER = LoggerFactory.getLogger(ControlLoopHandler.class);
60
61     private final ToscaConceptIdentifier participantType;
62     private final ToscaConceptIdentifier participantId;
63     private final ParticipantMessagePublisher publisher;
64
65     @Getter
66     private final Map<ToscaConceptIdentifier, ControlLoop> controlLoopMap = new LinkedHashMap<>();
67
68     @Getter
69     private final Map<UUID, ControlLoopElement> elementsOnThisParticipant = new LinkedHashMap<>();
70
71     @Getter
72     private List<ControlLoopElementListener> listeners = new ArrayList<>();
73
74     /**
75      * Constructor, set the participant ID and messageSender.
76      *
77      * @param parameters the parameters of the participant
78      * @param publisher the ParticipantMessage Publisher
79      */
80     public ControlLoopHandler(ParticipantParameters parameters, ParticipantMessagePublisher publisher) {
81         this.participantType = parameters.getIntermediaryParameters().getParticipantType();
82         this.participantId = parameters.getIntermediaryParameters().getParticipantId();
83         this.publisher = publisher;
84     }
85
86     public void registerControlLoopElementListener(ControlLoopElementListener listener) {
87         listeners.add(listener);
88     }
89
90     /**
91      * Handle a control loop element state change message.
92      *
93      * @param id controlloop element id
94      * @param orderedState the current state
95      * @param newState the ordered state
96      * @return controlLoopElement the updated controlloop element
97      */
98     public ControlLoopElement updateControlLoopElementState(ToscaConceptIdentifier controlLoopId, UUID id,
99             ControlLoopOrderedState orderedState, ControlLoopState newState) {
100
101         if (id == null) {
102             LOGGER.warn("Cannot update Control loop element state, id is null");
103             return null;
104         }
105
106         for (var controlLoop : controlLoopMap.values()) {
107             var element = controlLoop.getElements().get(id);
108             if (element != null) {
109                 element.setState(newState);
110             }
111             var checkOpt = controlLoop.getElements().values().stream()
112                     .filter(clElement -> !newState.equals(clElement.getState())).findAny();
113             if (checkOpt.isEmpty()) {
114                 controlLoop.setState(newState);
115                 controlLoop.setOrderedState(orderedState);
116             }
117         }
118
119         var clElement = elementsOnThisParticipant.get(id);
120         if (clElement != null) {
121             var controlLoopStateChangeAck = new ControlLoopAck(ParticipantMessageType.CONTROLLOOP_STATECHANGE_ACK);
122             controlLoopStateChangeAck.setParticipantId(participantId);
123             controlLoopStateChangeAck.setParticipantType(participantType);
124             controlLoopStateChangeAck.setControlLoopId(controlLoopId);
125             clElement.setOrderedState(orderedState);
126             clElement.setState(newState);
127             controlLoopStateChangeAck.getControlLoopResultMap().put(clElement.getId(), new ControlLoopElementAck(
128                     newState, true, "Control loop element {} state changed to {}\", id, newState)"));
129             LOGGER.debug("Control loop element {} state changed to {}", id, newState);
130             controlLoopStateChangeAck.setMessage("ControlLoopElement state changed to {} " + newState);
131             controlLoopStateChangeAck.setResult(true);
132             publisher.sendControlLoopAck(controlLoopStateChangeAck);
133             return clElement;
134         }
135         return null;
136     }
137
138     /**
139      * Handle a control loop element statistics.
140      *
141      * @param id controlloop element id
142      * @param elementStatistics control loop element Statistics
143      */
144     public void updateControlLoopElementStatistics(UUID id, ClElementStatistics elementStatistics) {
145         var clElement = elementsOnThisParticipant.get(id);
146         if (clElement != null) {
147             elementStatistics.setParticipantId(participantId);
148             elementStatistics.setId(id);
149             clElement.setClElementStatistics(elementStatistics);
150         }
151     }
152
153     /**
154      * Handle a control loop state change message.
155      *
156      * @param stateChangeMsg the state change message
157      */
158     public void handleControlLoopStateChange(ControlLoopStateChange stateChangeMsg) {
159         if (stateChangeMsg.getControlLoopId() == null) {
160             return;
161         }
162
163         var controlLoop = controlLoopMap.get(stateChangeMsg.getControlLoopId());
164
165         if (controlLoop == null) {
166             var controlLoopAck = new ControlLoopAck(ParticipantMessageType.CONTROL_LOOP_STATE_CHANGE);
167             controlLoopAck.setParticipantId(participantId);
168             controlLoopAck.setParticipantType(participantType);
169             controlLoopAck.setMessage("Control loop " + stateChangeMsg.getControlLoopId()
170                     + " does not use this participant " + participantId);
171             controlLoopAck.setResult(false);
172             controlLoopAck.setResponseTo(stateChangeMsg.getMessageId());
173             controlLoopAck.setControlLoopId(stateChangeMsg.getControlLoopId());
174             publisher.sendControlLoopAck(controlLoopAck);
175             LOGGER.debug("Control loop {} does not use this participant", stateChangeMsg.getControlLoopId());
176             return;
177         }
178
179         handleState(controlLoop, stateChangeMsg.getOrderedState());
180     }
181
182     /**
183      * Method to handle state changes.
184      *
185      * @param controlLoop participant response
186      * @param orderedState controlloop ordered state
187      */
188     private void handleState(final ControlLoop controlLoop, ControlLoopOrderedState orderedState) {
189         switch (orderedState) {
190             case UNINITIALISED:
191                 handleUninitialisedState(controlLoop, orderedState);
192                 break;
193             case PASSIVE:
194                 handlePassiveState(controlLoop, orderedState);
195                 break;
196             case RUNNING:
197                 handleRunningState(controlLoop, orderedState);
198                 break;
199             default:
200                 LOGGER.debug("StateChange message has no state, state is null {}", controlLoop.getDefinition());
201                 break;
202         }
203     }
204
205     /**
206      * Handle a control loop update message.
207      *
208      * @param updateMsg the update message
209      */
210     public void handleControlLoopUpdate(ControlLoopUpdate updateMsg,
211             List<ControlLoopElementDefinition> clElementDefinitions) {
212
213         if (!updateMsg.appliesTo(participantType, participantId)) {
214             return;
215         }
216
217         var controlLoop = controlLoopMap.get(updateMsg.getControlLoopId());
218
219         // TODO: Updates to existing ControlLoops are not supported yet (Addition/Removal of ControlLoop
220         // elements to existing ControlLoop has to be supported).
221         if (controlLoop != null) {
222             var controlLoopUpdateAck = new ControlLoopAck(ParticipantMessageType.CONTROLLOOP_UPDATE_ACK);
223             controlLoopUpdateAck.setParticipantId(participantId);
224             controlLoopUpdateAck.setParticipantType(participantType);
225
226             controlLoopUpdateAck.setMessage("Control loop " + updateMsg.getControlLoopId()
227                     + " already defined on participant " + participantId);
228             controlLoopUpdateAck.setResult(false);
229             controlLoopUpdateAck.setResponseTo(updateMsg.getMessageId());
230             controlLoopUpdateAck.setControlLoopId(updateMsg.getControlLoopId());
231             publisher.sendControlLoopAck(controlLoopUpdateAck);
232             return;
233         }
234
235         if (updateMsg.getParticipantUpdatesList().isEmpty()) {
236             LOGGER.warn("No ControlLoopElement updates in message {}", updateMsg.getControlLoopId());
237             return;
238         }
239
240         var clElements = storeElementsOnThisParticipant(updateMsg.getParticipantUpdatesList());
241
242         try {
243             for (var element : clElements) {
244                 var clElementNodeTemplate =
245                         getClElementNodeTemplate(clElementDefinitions, element.getDefinition());
246                 for (var clElementListener : listeners) {
247                     clElementListener.controlLoopElementUpdate(updateMsg.getControlLoopId(), element,
248                             clElementNodeTemplate);
249                 }
250             }
251         } catch (PfModelException e) {
252             LOGGER.debug("Control loop element update failed {}", updateMsg.getControlLoopId());
253         }
254
255         var clElementMap = prepareClElementMap(clElements);
256         controlLoop = new ControlLoop();
257         controlLoop.setDefinition(updateMsg.getControlLoopId());
258         controlLoop.setElements(clElementMap);
259         controlLoopMap.put(updateMsg.getControlLoopId(), controlLoop);
260     }
261
262     private ToscaNodeTemplate getClElementNodeTemplate(List<ControlLoopElementDefinition> clElementDefinitions,
263             ToscaConceptIdentifier clElementDefId) {
264         for (var clElementDefinition : clElementDefinitions) {
265             if (clElementDefinition.getClElementDefinitionId().equals(clElementDefId)) {
266                 return clElementDefinition.getControlLoopElementToscaNodeTemplate();
267             }
268         }
269         return null;
270     }
271
272     private List<ControlLoopElement> storeElementsOnThisParticipant(List<ParticipantUpdates> participantUpdates) {
273         var clElementMap = participantUpdates.stream()
274                 .flatMap(participantUpdate -> participantUpdate.getControlLoopElementList().stream())
275                 .filter(element -> participantType.equals(element.getParticipantType())).collect(Collectors.toList());
276
277         for (var element : clElementMap) {
278             elementsOnThisParticipant.put(element.getId(), element);
279         }
280         return clElementMap;
281     }
282
283     private Map<UUID, ControlLoopElement> prepareClElementMap(List<ControlLoopElement> clElements) {
284         Map<UUID, ControlLoopElement> clElementMap = new LinkedHashMap<>();
285         for (var element : clElements) {
286             clElementMap.put(element.getId(), element);
287         }
288         return clElementMap;
289     }
290
291     /**
292      * Method to handle when the new state from participant is UNINITIALISED state.
293      *
294      * @param controlLoop participant response
295      * @param orderedState orderedState
296      */
297     private void handleUninitialisedState(final ControlLoop controlLoop, final ControlLoopOrderedState orderedState) {
298         handleStateChange(controlLoop, orderedState);
299         controlLoopMap.remove(controlLoop.getDefinition());
300         controlLoop.getElements().values().forEach(element -> elementsOnThisParticipant.remove(element.getId()));
301     }
302
303     /**
304      * Method to handle when the new state from participant is PASSIVE state.
305      *
306      * @param controlLoop participant response
307      * @param orderedState orderedState
308      */
309     private void handlePassiveState(final ControlLoop controlLoop, final ControlLoopOrderedState orderedState) {
310         handleStateChange(controlLoop, orderedState);
311     }
312
313     /**
314      * Method to handle when the new state from participant is RUNNING state.
315      *
316      * @param controlLoop participant response
317      * @param orderedState orderedState
318      */
319     private void handleRunningState(final ControlLoop controlLoop, final ControlLoopOrderedState orderedState) {
320         handleStateChange(controlLoop, orderedState);
321     }
322
323     /**
324      * Method to update the state of control loop elements.
325      *
326      * @param controlLoop participant status in memory
327      * @param orderedState orderedState the new ordered state the participant should have
328      */
329     private void handleStateChange(ControlLoop controlLoop, final ControlLoopOrderedState orderedState) {
330
331         if (orderedState.equals(controlLoop.getOrderedState())) {
332             var controlLoopAck = new ControlLoopAck(ParticipantMessageType.CONTROL_LOOP_STATE_CHANGE);
333             controlLoopAck.setParticipantId(participantId);
334             controlLoopAck.setParticipantType(participantType);
335             controlLoopAck.setMessage("Control loop is already in state " + orderedState);
336             controlLoopAck.setResult(false);
337             controlLoopAck.setControlLoopId(controlLoop.getDefinition());
338             publisher.sendControlLoopAck(controlLoopAck);
339             return;
340         }
341
342         for (var clElementListener : listeners) {
343             try {
344                 for (var element : controlLoop.getElements().values()) {
345                     clElementListener.controlLoopElementStateChange(controlLoop.getDefinition(), element.getId(),
346                             element.getState(), orderedState);
347                 }
348             } catch (PfModelException e) {
349                 LOGGER.debug("Control loop element update failed {}", controlLoop.getDefinition());
350             }
351         }
352     }
353
354     /**
355      * Get control loops as a {@link ConrolLoops} class.
356      *
357      * @return the control loops
358      */
359     public ControlLoops getControlLoops() {
360         var controlLoops = new ControlLoops();
361         controlLoops.setControlLoopList(new ArrayList<>(controlLoopMap.values()));
362         return controlLoops;
363     }
364 }