7cf83db9d8e92a60f1af33d80b32b7236c0cb5f1
[policy/clamp.git] /
1 /*-
2  * ============LICENSE_START=======================================================
3  *  Copyright (C) 2023-2024 Nordix Foundation.
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.clamp.acm.participant.intermediary.handler;
22
23 import java.util.List;
24 import java.util.Map;
25 import java.util.UUID;
26 import lombok.RequiredArgsConstructor;
27 import org.onap.policy.clamp.acm.participant.intermediary.comm.ParticipantMessagePublisher;
28 import org.onap.policy.clamp.models.acm.concepts.AcElementDeployAck;
29 import org.onap.policy.clamp.models.acm.concepts.AcTypeState;
30 import org.onap.policy.clamp.models.acm.concepts.AutomationComposition;
31 import org.onap.policy.clamp.models.acm.concepts.AutomationCompositionElement;
32 import org.onap.policy.clamp.models.acm.concepts.AutomationCompositionElementDefinition;
33 import org.onap.policy.clamp.models.acm.concepts.AutomationCompositionElementInfo;
34 import org.onap.policy.clamp.models.acm.concepts.AutomationCompositionInfo;
35 import org.onap.policy.clamp.models.acm.concepts.DeployState;
36 import org.onap.policy.clamp.models.acm.concepts.LockState;
37 import org.onap.policy.clamp.models.acm.concepts.ParticipantDefinition;
38 import org.onap.policy.clamp.models.acm.concepts.ParticipantState;
39 import org.onap.policy.clamp.models.acm.concepts.StateChangeResult;
40 import org.onap.policy.clamp.models.acm.concepts.SubState;
41 import org.onap.policy.clamp.models.acm.messages.kafka.participant.AutomationCompositionDeployAck;
42 import org.onap.policy.clamp.models.acm.messages.kafka.participant.ParticipantMessageType;
43 import org.onap.policy.clamp.models.acm.messages.kafka.participant.ParticipantPrimeAck;
44 import org.onap.policy.clamp.models.acm.messages.kafka.participant.ParticipantStatus;
45 import org.onap.policy.clamp.models.acm.utils.AcmUtils;
46 import org.onap.policy.models.tosca.authorative.concepts.ToscaConceptIdentifier;
47 import org.slf4j.Logger;
48 import org.slf4j.LoggerFactory;
49 import org.springframework.stereotype.Component;
50
51 @Component
52 @RequiredArgsConstructor
53 public class AutomationCompositionOutHandler {
54     private static final Logger LOGGER = LoggerFactory.getLogger(AutomationCompositionOutHandler.class);
55
56     private final ParticipantMessagePublisher publisher;
57     private final CacheProvider cacheProvider;
58
59     /**
60      * Handle a automation composition element stage change message.
61      *
62      * @param instance the automationComposition Id
63      * @param elementId the automationComposition Element Id
64      * @param stage the next stage
65      * @param message the message
66      * @param stateChangeResult the indicator if error occurs
67      */
68     public void updateAutomationCompositionElementStage(UUID instance, UUID elementId,
69         StateChangeResult stateChangeResult, int stage, String message) {
70         if (!validateData(instance, elementId, stateChangeResult)) {
71             return;
72         }
73
74         var automationComposition = cacheProvider.getAutomationComposition(instance);
75         if (automationComposition == null) {
76             LOGGER.error("Cannot update Automation composition element stage, Automation composition id {} not present",
77                 instance);
78             return;
79         }
80
81         var element = automationComposition.getElements().get(elementId);
82         if (element == null) {
83             var msg = "Cannot update Automation composition element stage, AC Element id {} not present";
84             LOGGER.error(msg, elementId);
85             return;
86         }
87
88         var automationCompositionStateChangeAck =
89             new AutomationCompositionDeployAck(ParticipantMessageType.AUTOMATION_COMPOSITION_STATECHANGE_ACK);
90         automationCompositionStateChangeAck.setParticipantId(cacheProvider.getParticipantId());
91         automationCompositionStateChangeAck.setMessage(AcmUtils.validatedMessage(message));
92         automationCompositionStateChangeAck.setResponseTo(cacheProvider.getMsgIdentification().get(element.getId()));
93         automationCompositionStateChangeAck.setStateChangeResult(stateChangeResult);
94         automationCompositionStateChangeAck.setStage(stage);
95         automationCompositionStateChangeAck.setAutomationCompositionId(instance);
96         automationCompositionStateChangeAck.getAutomationCompositionResultMap().put(element.getId(),
97             new AcElementDeployAck(element.getDeployState(), element.getLockState(), element.getOperationalState(),
98                 element.getUseState(), element.getOutProperties(), true, message));
99         LOGGER.debug("Automation composition element {} stage changed to {}", elementId, stage);
100         automationCompositionStateChangeAck.setResult(true);
101         publisher.sendAutomationCompositionAck(automationCompositionStateChangeAck);
102         cacheProvider.getMsgIdentification().remove(element.getId());
103     }
104
105     private boolean validateData(UUID instance, UUID elementId, StateChangeResult stateChangeResult) {
106         if (instance == null || elementId == null) {
107             LOGGER.error("Not valid Ac instance, id is null");
108             return false;
109         }
110         if (stateChangeResult == null) {
111             LOGGER.error("Not valid Ac instance, stateChangeResult is null");
112             return false;
113         }
114         if (!StateChangeResult.NO_ERROR.equals(stateChangeResult)
115                 && !StateChangeResult.FAILED.equals(stateChangeResult)) {
116             LOGGER.error("Not valid Ac instance, stateChangeResult is not valid");
117             return false;
118         }
119         return true;
120     }
121
122     /**
123      * Handle a automation composition element state change message.
124      *
125      * @param instance the automationComposition Id
126      * @param elementId the automationComposition Element Id
127      * @param deployState the DeployState state
128      * @param lockState the LockState state
129      * @param message the message
130      * @param stateChangeResult the indicator if error occurs
131      */
132     public void updateAutomationCompositionElementState(UUID instance, UUID elementId,
133             DeployState deployState, LockState lockState, StateChangeResult stateChangeResult, String message) {
134         if (!validateData(instance, elementId, stateChangeResult)) {
135             return;
136         }
137
138         if ((deployState != null && lockState != null) || (deployState == null && lockState == null)
139                 || AcmUtils.isInTransitionalState(deployState, lockState, SubState.NONE)) {
140             LOGGER.error("state error {} and {} cannot be handled", deployState, lockState);
141             return;
142         }
143
144         var automationComposition = cacheProvider.getAutomationComposition(instance);
145         if (automationComposition == null) {
146             LOGGER.error("Cannot update Automation composition element state, Automation composition id {} not present",
147                 instance);
148             return;
149         }
150
151         var element = automationComposition.getElements().get(elementId);
152         if (element == null) {
153             var msg = "Cannot update Automation composition element state, AC Element id {} not present";
154             LOGGER.error(msg, elementId);
155             return;
156         }
157
158         if (deployState != null && !SubState.NONE.equals(element.getSubState())) {
159             handleSubState(automationComposition, element);
160             if (!StateChangeResult.NO_ERROR.equals(stateChangeResult)) {
161                 stateChangeResult = StateChangeResult.NO_ERROR;
162                 LOGGER.warn("SubState has always NO_ERROR result!");
163             }
164         } else if (deployState != null) {
165             handleDeployState(automationComposition, element, deployState);
166         }
167         if (lockState != null) {
168             handleLockState(automationComposition, element, lockState);
169         }
170
171         var automationCompositionStateChangeAck =
172                 new AutomationCompositionDeployAck(ParticipantMessageType.AUTOMATION_COMPOSITION_STATECHANGE_ACK);
173         automationCompositionStateChangeAck.setParticipantId(cacheProvider.getParticipantId());
174         automationCompositionStateChangeAck.setReplicaId(cacheProvider.getReplicaId());
175         automationCompositionStateChangeAck.setMessage(AcmUtils.validatedMessage(message));
176         automationCompositionStateChangeAck.setResponseTo(cacheProvider.getMsgIdentification().get(element.getId()));
177         automationCompositionStateChangeAck.setStateChangeResult(stateChangeResult);
178         automationCompositionStateChangeAck.setAutomationCompositionId(instance);
179         automationCompositionStateChangeAck.getAutomationCompositionResultMap().put(element.getId(),
180                 new AcElementDeployAck(element.getDeployState(), element.getLockState(), element.getOperationalState(),
181                         element.getUseState(), element.getOutProperties(), true, message));
182         LOGGER.debug("Automation composition element {} state changed to {}", elementId, deployState);
183         automationCompositionStateChangeAck.setResult(true);
184         publisher.sendAutomationCompositionAck(automationCompositionStateChangeAck);
185         cacheProvider.getMsgIdentification().remove(element.getId());
186     }
187
188     private void handleDeployState(AutomationComposition automationComposition, AutomationCompositionElement element,
189             DeployState deployState) {
190         element.setDeployState(deployState);
191         element.setLockState(DeployState.DEPLOYED.equals(element.getDeployState()) ? LockState.LOCKED : LockState.NONE);
192         var checkOpt = automationComposition.getElements().values().stream()
193                 .filter(acElement -> !deployState.equals(acElement.getDeployState())).findAny();
194         if (checkOpt.isEmpty()) {
195             if (DeployState.DEPLOYED.equals(automationComposition.getDeployState())
196                     && automationComposition.getCompositionTargetId() != null) {
197                 // migration scenario
198                 automationComposition.setCompositionId(automationComposition.getCompositionTargetId());
199                 automationComposition.setCompositionTargetId(null);
200             }
201             automationComposition.setDeployState(deployState);
202             automationComposition.setLockState(element.getLockState());
203             automationComposition.setSubState(SubState.NONE);
204
205             if (DeployState.DELETED.equals(deployState)) {
206                 cacheProvider.removeAutomationComposition(automationComposition.getInstanceId());
207             }
208         }
209     }
210
211     private void handleLockState(AutomationComposition automationComposition, AutomationCompositionElement element,
212             LockState lockState) {
213         element.setLockState(lockState);
214         var checkOpt = automationComposition.getElements().values().stream()
215                 .filter(acElement -> !lockState.equals(acElement.getLockState())).findAny();
216         if (checkOpt.isEmpty()) {
217             automationComposition.setLockState(lockState);
218             automationComposition.setSubState(SubState.NONE);
219         }
220     }
221
222     private void handleSubState(AutomationComposition automationComposition, AutomationCompositionElement element) {
223         element.setSubState(SubState.NONE);
224         var checkOpt = automationComposition.getElements().values().stream()
225                 .filter(acElement -> !SubState.NONE.equals(acElement.getSubState())).findAny();
226         if (checkOpt.isEmpty()) {
227             automationComposition.setSubState(SubState.NONE);
228         }
229     }
230
231     /**
232      * Send Ac Element Info.
233      *
234      * @param automationCompositionId the automationComposition Id
235      * @param elementId the automationComposition Element id
236      * @param useState the use State
237      * @param operationalState the operational State
238      * @param outProperties the output Properties Map
239      */
240     public void sendAcElementInfo(UUID automationCompositionId, UUID elementId, String useState,
241             String operationalState, Map<String, Object> outProperties) {
242
243         if (automationCompositionId == null || elementId == null) {
244             LOGGER.error("Cannot update Automation composition element state, id is null");
245             return;
246         }
247
248         var automationComposition = cacheProvider.getAutomationComposition(automationCompositionId);
249         if (automationComposition == null) {
250             LOGGER.error("Cannot update Automation composition element state, Automation composition id {} not present",
251                     automationCompositionId);
252             return;
253         }
254
255         var element = automationComposition.getElements().get(elementId);
256         if (element == null) {
257             var msg = "Cannot update Automation composition element state, AC Element id {} not present";
258             LOGGER.error(msg, elementId);
259             return;
260         }
261         element.setOperationalState(operationalState);
262         element.setUseState(useState);
263         element.setOutProperties(outProperties);
264
265         var acInfo = new AutomationCompositionInfo();
266         acInfo.setAutomationCompositionId(automationCompositionId);
267         acInfo.setDeployState(automationComposition.getDeployState());
268         acInfo.setLockState(automationComposition.getLockState());
269         acInfo.setElements(List.of(getAutomationCompositionElementInfo(element)));
270         var statusMsg = createParticipantStatus();
271         statusMsg.setCompositionId(automationComposition.getCompositionId());
272         statusMsg.setAutomationCompositionInfoList(List.of(acInfo));
273         publisher.sendParticipantStatus(statusMsg);
274     }
275
276     /**
277      * Get AutomationCompositionElementInfo from AutomationCompositionElement.
278      *
279      * @param element the AutomationCompositionElement
280      * @return the AutomationCompositionElementInfo
281      */
282     public AutomationCompositionElementInfo getAutomationCompositionElementInfo(AutomationCompositionElement element) {
283         var elementInfo = new AutomationCompositionElementInfo();
284         elementInfo.setAutomationCompositionElementId(element.getId());
285         elementInfo.setDeployState(element.getDeployState());
286         elementInfo.setLockState(element.getLockState());
287         elementInfo.setOperationalState(element.getOperationalState());
288         elementInfo.setUseState(element.getUseState());
289         elementInfo.setOutProperties(element.getOutProperties());
290         return elementInfo;
291     }
292
293     /**
294      * Update Composition State for prime and deprime.
295      *
296      * @param compositionId the composition id
297      * @param state the Composition State
298      * @param stateChangeResult the indicator if error occurs
299      * @param message the message
300      */
301     public void updateCompositionState(UUID compositionId, AcTypeState state, StateChangeResult stateChangeResult,
302             String message) {
303         if (compositionId == null) {
304             LOGGER.error("Cannot update Automation composition definition state, id is null");
305             return;
306         }
307
308         if (stateChangeResult == null) {
309             LOGGER.error("Cannot update Automation composition definition state, stateChangeResult is null");
310             return;
311         }
312         if (!StateChangeResult.NO_ERROR.equals(stateChangeResult)
313                 && !StateChangeResult.FAILED.equals(stateChangeResult)) {
314             LOGGER.error("Cannot update Automation composition definition state, stateChangeResult is not valid");
315             return;
316         }
317
318         if ((state == null) || AcTypeState.PRIMING.equals(state) || AcTypeState.DEPRIMING.equals(state)) {
319             LOGGER.error("state invalid {} cannot be handled", state);
320             return;
321         }
322
323         var participantPrimeAck = new ParticipantPrimeAck();
324         participantPrimeAck.setCompositionId(compositionId);
325         participantPrimeAck.setMessage(AcmUtils.validatedMessage(message));
326         participantPrimeAck.setResult(true);
327         participantPrimeAck.setResponseTo(cacheProvider.getMsgIdentification().get(compositionId));
328         participantPrimeAck.setCompositionState(state);
329         participantPrimeAck.setStateChangeResult(stateChangeResult);
330         participantPrimeAck.setParticipantId(cacheProvider.getParticipantId());
331         participantPrimeAck.setReplicaId(cacheProvider.getReplicaId());
332         participantPrimeAck.setState(ParticipantState.ON_LINE);
333         publisher.sendParticipantPrimeAck(participantPrimeAck);
334         cacheProvider.getMsgIdentification().remove(compositionId);
335         if (AcTypeState.COMMISSIONED.equals(state) && StateChangeResult.NO_ERROR.equals(stateChangeResult)) {
336             cacheProvider.removeElementDefinition(compositionId);
337         }
338     }
339
340     /**
341      * Send Composition Definition Info.
342      *
343      * @param compositionId the composition id
344      * @param elementId the Composition Definition Element id
345      * @param outProperties the output Properties Map
346      */
347     public void sendAcDefinitionInfo(UUID compositionId, ToscaConceptIdentifier elementId,
348             Map<String, Object> outProperties) {
349         if (compositionId == null) {
350             LOGGER.error("Cannot send Composition outProperties, id is null");
351             return;
352         }
353         var statusMsg = createParticipantStatus();
354         statusMsg.setCompositionId(compositionId);
355         var acElementDefsMap = cacheProvider.getAcElementsDefinitions();
356         var acElementsDefinitions = acElementDefsMap.get(compositionId);
357         if (acElementsDefinitions == null) {
358             LOGGER.error("Cannot send Composition outProperties, id {} is null", compositionId);
359             return;
360         }
361         var acElementDefinition = getAutomationCompositionElementDefinition(acElementsDefinitions, elementId);
362         if (acElementDefinition == null) {
363             LOGGER.error("Cannot send Composition outProperties, elementId {} not present", elementId);
364             return;
365         }
366         acElementDefinition.setOutProperties(outProperties);
367         var participantDefinition = new ParticipantDefinition();
368         participantDefinition.setParticipantId(cacheProvider.getParticipantId());
369         participantDefinition.setAutomationCompositionElementDefinitionList(List.of(acElementDefinition));
370         statusMsg.setParticipantDefinitionUpdates(List.of(participantDefinition));
371         publisher.sendParticipantStatus(statusMsg);
372     }
373
374     private AutomationCompositionElementDefinition getAutomationCompositionElementDefinition(
375             Map<ToscaConceptIdentifier, AutomationCompositionElementDefinition> acElementsDefinition,
376             ToscaConceptIdentifier elementId) {
377
378         if (elementId == null) {
379             if (acElementsDefinition.size() == 1) {
380                 return acElementsDefinition.values().iterator().next();
381             }
382             return null;
383         }
384         return acElementsDefinition.get(elementId);
385     }
386
387     private ParticipantStatus createParticipantStatus() {
388         var statusMsg = new ParticipantStatus();
389         statusMsg.setParticipantId(cacheProvider.getParticipantId());
390         statusMsg.setReplicaId(cacheProvider.getReplicaId());
391         statusMsg.setState(ParticipantState.ON_LINE);
392         statusMsg.setParticipantSupportedElementType(cacheProvider.getSupportedAcElementTypes());
393         return statusMsg;
394     }
395 }