6d94efb0f5dad58e4b2a9508a92c05f27d32c2ca
[policy/clamp.git] /
1 /*-
2  * ============LICENSE_START=======================================================
3  *  Copyright (C) 2021-2024 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.acm.participant.intermediary.handler;
23
24 import java.util.List;
25 import java.util.Map;
26 import java.util.UUID;
27 import java.util.stream.Collectors;
28 import lombok.RequiredArgsConstructor;
29 import org.onap.policy.clamp.acm.participant.intermediary.api.CompositionElementDto;
30 import org.onap.policy.clamp.acm.participant.intermediary.api.ElementState;
31 import org.onap.policy.clamp.acm.participant.intermediary.api.InstanceElementDto;
32 import org.onap.policy.clamp.acm.participant.intermediary.comm.ParticipantMessagePublisher;
33 import org.onap.policy.clamp.models.acm.concepts.AcElementDeploy;
34 import org.onap.policy.clamp.models.acm.concepts.AutomationComposition;
35 import org.onap.policy.clamp.models.acm.concepts.AutomationCompositionElement;
36 import org.onap.policy.clamp.models.acm.concepts.DeployState;
37 import org.onap.policy.clamp.models.acm.concepts.LockState;
38 import org.onap.policy.clamp.models.acm.concepts.ParticipantDeploy;
39 import org.onap.policy.clamp.models.acm.concepts.ParticipantUtils;
40 import org.onap.policy.clamp.models.acm.concepts.StateChangeResult;
41 import org.onap.policy.clamp.models.acm.concepts.SubState;
42 import org.onap.policy.clamp.models.acm.messages.kafka.participant.AutomationCompositionDeploy;
43 import org.onap.policy.clamp.models.acm.messages.kafka.participant.AutomationCompositionDeployAck;
44 import org.onap.policy.clamp.models.acm.messages.kafka.participant.AutomationCompositionMigration;
45 import org.onap.policy.clamp.models.acm.messages.kafka.participant.AutomationCompositionStateChange;
46 import org.onap.policy.clamp.models.acm.messages.kafka.participant.ParticipantMessageType;
47 import org.onap.policy.clamp.models.acm.messages.kafka.participant.PropertiesUpdate;
48 import org.onap.policy.clamp.models.acm.messages.rest.instantiation.DeployOrder;
49 import org.onap.policy.clamp.models.acm.utils.AcmUtils;
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 automation compositions in the participant.
56  */
57 @Component
58 @RequiredArgsConstructor
59 public class AutomationCompositionHandler {
60     private static final Logger LOGGER = LoggerFactory.getLogger(AutomationCompositionHandler.class);
61
62     private final CacheProvider cacheProvider;
63     private final ParticipantMessagePublisher publisher;
64     private final ThreadHandler listener;
65
66     /**
67      * Handle a automation composition state change message.
68      *
69      * @param stateChangeMsg the state change message
70      */
71     public void handleAutomationCompositionStateChange(AutomationCompositionStateChange stateChangeMsg) {
72         if (stateChangeMsg.getAutomationCompositionId() == null) {
73             return;
74         }
75
76         var automationComposition = cacheProvider.getAutomationComposition(stateChangeMsg.getAutomationCompositionId());
77
78         if (automationComposition == null) {
79             if (DeployOrder.DELETE.equals(stateChangeMsg.getDeployOrderedState())) {
80                 var automationCompositionAck = new AutomationCompositionDeployAck(
81                         ParticipantMessageType.AUTOMATION_COMPOSITION_STATECHANGE_ACK);
82                 automationCompositionAck.setParticipantId(cacheProvider.getParticipantId());
83                 automationCompositionAck.setReplicaId(cacheProvider.getReplicaId());
84                 automationCompositionAck.setMessage("Already deleted or never used");
85                 automationCompositionAck.setResult(true);
86                 automationCompositionAck.setStateChangeResult(StateChangeResult.NO_ERROR);
87                 automationCompositionAck.setResponseTo(stateChangeMsg.getMessageId());
88                 automationCompositionAck.setAutomationCompositionId(stateChangeMsg.getAutomationCompositionId());
89                 publisher.sendAutomationCompositionAck(automationCompositionAck);
90             } else {
91                 LOGGER.debug("Automation composition {} does not use this participant",
92                         stateChangeMsg.getAutomationCompositionId());
93             }
94             return;
95         }
96
97         switch (stateChangeMsg.getDeployOrderedState()) {
98             case UNDEPLOY -> handleUndeployState(stateChangeMsg.getMessageId(), automationComposition,
99                     stateChangeMsg.getStartPhase());
100             case DELETE -> handleDeleteState(stateChangeMsg.getMessageId(), automationComposition,
101                     stateChangeMsg.getStartPhase());
102             default ->
103                     LOGGER.error("StateChange message has no state, state is null {}", automationComposition.getKey());
104         }
105     }
106
107     /**
108      * Handle a automation composition properties update message.
109      *
110      * @param updateMsg the properties update message
111      */
112     public void handleAcPropertyUpdate(PropertiesUpdate updateMsg) {
113
114         if (updateMsg.getParticipantUpdatesList().isEmpty()) {
115             LOGGER.warn("No AutomationCompositionElement updates in message {}",
116                     updateMsg.getAutomationCompositionId());
117             return;
118         }
119
120         for (var participantDeploy : updateMsg.getParticipantUpdatesList()) {
121             if (cacheProvider.getParticipantId().equals(participantDeploy.getParticipantId())) {
122                 var automationComposition = cacheProvider.getAutomationComposition(
123                         updateMsg.getAutomationCompositionId());
124                 automationComposition.setDeployState(DeployState.UPDATING);
125                 var acCopy = new AutomationComposition(automationComposition);
126                 updateExistingElementsOnThisParticipant(updateMsg.getAutomationCompositionId(), participantDeploy);
127
128                 callParticipantUpdateProperty(updateMsg.getMessageId(), participantDeploy.getAcElementList(), acCopy);
129             }
130         }
131     }
132
133     /**
134      * Handle a automation composition Deploy message.
135      *
136      * @param deployMsg the Deploy message
137      */
138     public void handleAutomationCompositionDeploy(AutomationCompositionDeploy deployMsg) {
139
140         if (deployMsg.getParticipantUpdatesList().isEmpty()) {
141             LOGGER.warn("No AutomationCompositionElement deploy in message {}", deployMsg.getAutomationCompositionId());
142             return;
143         }
144
145         for (var participantDeploy : deployMsg.getParticipantUpdatesList()) {
146             if (cacheProvider.getParticipantId().equals(participantDeploy.getParticipantId())) {
147                 if (deployMsg.isFirstStartPhase()) {
148                     cacheProvider.initializeAutomationComposition(deployMsg.getCompositionId(),
149                             deployMsg.getAutomationCompositionId(), participantDeploy);
150                 }
151                 callParticipanDeploy(deployMsg.getMessageId(), participantDeploy.getAcElementList(),
152                         deployMsg.getStartPhase(), deployMsg.getAutomationCompositionId());
153             }
154         }
155     }
156
157     private void callParticipanDeploy(UUID messageId, List<AcElementDeploy> acElementDeployList,
158             Integer startPhaseMsg, UUID instanceId) {
159         var automationComposition = cacheProvider.getAutomationComposition(instanceId);
160         automationComposition.setDeployState(DeployState.DEPLOYING);
161         for (var elementDeploy : acElementDeployList) {
162             var element = automationComposition.getElements().get(elementDeploy.getId());
163             var compositionInProperties = cacheProvider
164                 .getCommonProperties(automationComposition.getCompositionId(), element.getDefinition());
165             int startPhase = ParticipantUtils.findStartPhase(compositionInProperties);
166             if (startPhaseMsg.equals(startPhase)) {
167                 var compositionElement = cacheProvider.createCompositionElementDto(
168                         automationComposition.getCompositionId(), element, compositionInProperties);
169                 var instanceElement = new InstanceElementDto(instanceId, elementDeploy.getId(),
170                     elementDeploy.getToscaServiceTemplateFragment(),
171                     elementDeploy.getProperties(), element.getOutProperties());
172                 listener.deploy(messageId, compositionElement, instanceElement);
173             }
174         }
175     }
176
177     private void callParticipantUpdateProperty(UUID messageId, List<AcElementDeploy> acElements,
178         AutomationComposition acCopy) {
179         var instanceElementDtoMap = cacheProvider.getInstanceElementDtoMap(acCopy);
180         var instanceElementDtoMapUpdated = cacheProvider.getInstanceElementDtoMap(
181             cacheProvider.getAutomationComposition(acCopy.getInstanceId()));
182         var compositionElementDtoMap = cacheProvider.getCompositionElementDtoMap(acCopy);
183         for (var acElement : acElements) {
184             listener.update(messageId, compositionElementDtoMap.get(acElement.getId()),
185                 instanceElementDtoMap.get(acElement.getId()), instanceElementDtoMapUpdated.get(acElement.getId()));
186         }
187     }
188
189     private void migrateExistingElementsOnThisParticipant(UUID instanceId, UUID compositionTargetId,
190         ParticipantDeploy participantDeploy, int stage) {
191         var automationComposition = cacheProvider.getAutomationComposition(instanceId);
192         var acElementList = automationComposition.getElements();
193         for (var element : participantDeploy.getAcElementList()) {
194             var compositionInProperties =
195                     cacheProvider.getCommonProperties(compositionTargetId, element.getDefinition());
196             var stageSet = ParticipantUtils.findStageSet(compositionInProperties);
197             if (stageSet.contains(stage)) {
198                 var acElement = acElementList.get(element.getId());
199                 if (acElement == null) {
200                     var newElement = CacheProvider.createAutomationCompositionElement(element);
201                     newElement.setParticipantId(participantDeploy.getParticipantId());
202                     newElement.setDeployState(DeployState.MIGRATING);
203                     newElement.setLockState(LockState.LOCKED);
204                     newElement.setStage(stage);
205
206                     acElementList.put(element.getId(), newElement);
207                     LOGGER.info("New Ac Element with id {} is added in Migration", element.getId());
208                 } else {
209                     AcmUtils.recursiveMerge(acElement.getProperties(), element.getProperties());
210                     acElement.setDeployState(DeployState.MIGRATING);
211                     acElement.setStage(stage);
212                     acElement.setDefinition(element.getDefinition());
213                 }
214             }
215         }
216         // Check for missing elements and remove them from cache
217         var elementsToRemove = findElementsToRemove(participantDeploy.getAcElementList(), acElementList);
218         for (var key : elementsToRemove) {
219             acElementList.remove(key);
220             LOGGER.info("Element with id {} is removed in Migration", key);
221         }
222     }
223
224     private void updateExistingElementsOnThisParticipant(UUID instanceId, ParticipantDeploy participantDeploy) {
225         var acElementList = cacheProvider.getAutomationComposition(instanceId).getElements();
226         for (var element : participantDeploy.getAcElementList()) {
227             var acElement = acElementList.get(element.getId());
228             AcmUtils.recursiveMerge(acElement.getProperties(), element.getProperties());
229             acElement.setDeployState(DeployState.UPDATING);
230             acElement.setSubState(SubState.NONE);
231             acElement.setDefinition(element.getDefinition());
232         }
233     }
234
235     private List<UUID> findElementsToRemove(List<AcElementDeploy> acElementDeployList, Map<UUID,
236             AutomationCompositionElement> acElementList) {
237         var acElementDeploySet = acElementDeployList.stream().map(AcElementDeploy::getId).collect(Collectors.toSet());
238         return acElementList.keySet().stream().filter(id -> !acElementDeploySet.contains(id)).toList();
239     }
240
241     /**
242      * Method to handle when the new state from participant is UNINITIALISED state.
243      *
244      * @param messageId the messageId
245      * @param automationComposition participant response
246      * @param startPhaseMsg startPhase from message
247      */
248     private void handleUndeployState(UUID messageId, final AutomationComposition automationComposition,
249             Integer startPhaseMsg) {
250         automationComposition.setCompositionTargetId(null);
251         automationComposition.setDeployState(DeployState.UNDEPLOYING);
252         var serviceTemplateFragment = cacheProvider
253                 .getServiceTemplateFragmentMap().get(automationComposition.getCompositionId());
254         for (var element : automationComposition.getElements().values()) {
255             var compositionInProperties = cacheProvider
256                 .getCommonProperties(automationComposition.getCompositionId(), element.getDefinition());
257             int startPhase = ParticipantUtils.findStartPhase(compositionInProperties);
258             if (startPhaseMsg.equals(startPhase)) {
259                 element.setDeployState(DeployState.UNDEPLOYING);
260                 var compositionElement = cacheProvider.createCompositionElementDto(
261                         automationComposition.getCompositionId(), element, compositionInProperties);
262                 var instanceElement = new InstanceElementDto(automationComposition.getInstanceId(), element.getId(),
263                         serviceTemplateFragment, element.getProperties(), element.getOutProperties());
264                 listener.undeploy(messageId, compositionElement, instanceElement);
265             }
266         }
267     }
268
269     private void handleDeleteState(UUID messageId, final AutomationComposition automationComposition,
270             Integer startPhaseMsg) {
271         automationComposition.setDeployState(DeployState.DELETING);
272         var serviceTemplateFragment = cacheProvider
273                 .getServiceTemplateFragmentMap().get(automationComposition.getCompositionId());
274         for (var element : automationComposition.getElements().values()) {
275             var compositionInProperties = cacheProvider
276                 .getCommonProperties(automationComposition.getCompositionId(), element.getDefinition());
277             int startPhase = ParticipantUtils.findStartPhase(compositionInProperties);
278             if (startPhaseMsg.equals(startPhase)) {
279                 element.setDeployState(DeployState.DELETING);
280                 element.setSubState(SubState.NONE);
281                 var compositionElement = cacheProvider.createCompositionElementDto(
282                         automationComposition.getCompositionId(), element, compositionInProperties);
283                 var instanceElement = new InstanceElementDto(automationComposition.getInstanceId(), element.getId(),
284                         serviceTemplateFragment, element.getProperties(), element.getOutProperties());
285                 listener.delete(messageId, compositionElement, instanceElement);
286             }
287         }
288     }
289
290     /**
291      * Handles AutomationComposition Migration.
292      *
293      * @param migrationMsg the AutomationCompositionMigration
294      */
295     public void handleAutomationCompositionMigration(AutomationCompositionMigration migrationMsg) {
296         if (migrationMsg.getAutomationCompositionId() == null || migrationMsg.getCompositionTargetId() == null) {
297             return;
298         }
299
300         var automationComposition = cacheProvider.getAutomationComposition(migrationMsg.getAutomationCompositionId());
301         if (automationComposition == null) {
302             LOGGER.debug("Automation composition {} does not use this participant",
303                     migrationMsg.getAutomationCompositionId());
304             return;
305         }
306         var acCopy = new AutomationComposition(automationComposition);
307         automationComposition.setCompositionTargetId(migrationMsg.getCompositionTargetId());
308         automationComposition.setDeployState(DeployState.MIGRATING);
309         for (var participantDeploy : migrationMsg.getParticipantUpdatesList()) {
310             if (cacheProvider.getParticipantId().equals(participantDeploy.getParticipantId())) {
311
312                 migrateExistingElementsOnThisParticipant(migrationMsg.getAutomationCompositionId(),
313                         migrationMsg.getCompositionTargetId(), participantDeploy, migrationMsg.getStage());
314
315                 callParticipantMigrate(migrationMsg.getMessageId(), participantDeploy.getAcElementList(),
316                     acCopy, migrationMsg.getCompositionTargetId(), migrationMsg.getStage());
317             }
318         }
319     }
320
321     private void callParticipantMigrate(UUID messageId, List<AcElementDeploy> acElements,
322             AutomationComposition acCopy, UUID compositionTargetId, int stage) {
323         var compositionElementMap = cacheProvider.getCompositionElementDtoMap(acCopy);
324         var instanceElementMap = cacheProvider.getInstanceElementDtoMap(acCopy);
325         var automationComposition = cacheProvider.getAutomationComposition(acCopy.getInstanceId());
326         var compositionElementTargetMap = cacheProvider.getCompositionElementDtoMap(automationComposition,
327             compositionTargetId);
328         var instanceElementMigrateMap = cacheProvider.getInstanceElementDtoMap(automationComposition);
329
330         // Call migrate for newly added and updated elements
331         for (var acElement : acElements) {
332             var compositionInProperties = cacheProvider
333                     .getCommonProperties(compositionTargetId, acElement.getDefinition());
334             var stageSet = ParticipantUtils.findStageSet(compositionInProperties);
335             if (stageSet.contains(stage)) {
336                 if (instanceElementMap.get(acElement.getId()) == null) {
337                     var compositionElementDto =
338                             new CompositionElementDto(acCopy.getCompositionId(), acElement.getDefinition(),
339                                     Map.of(), Map.of(), ElementState.NOT_PRESENT);
340                     var instanceElementDto = new InstanceElementDto(acCopy.getInstanceId(), acElement.getId(),
341                             null, Map.of(), Map.of(), ElementState.NOT_PRESENT);
342                     var compositionElementTargetDto = CacheProvider.changeStateToNew(
343                             compositionElementTargetMap.get(acElement.getId()));
344                     var instanceElementMigrateDto = CacheProvider
345                             .changeStateToNew(instanceElementMigrateMap.get(acElement.getId()));
346
347                     listener.migrate(messageId, compositionElementDto, compositionElementTargetDto, instanceElementDto,
348                             instanceElementMigrateDto, stage);
349                 } else {
350                     listener.migrate(messageId, compositionElementMap.get(acElement.getId()),
351                             compositionElementTargetMap.get(acElement.getId()),
352                             instanceElementMap.get(acElement.getId()), instanceElementMigrateMap.get(acElement.getId()),
353                             stage);
354                 }
355             }
356         }
357         if (stage == 0) {
358             // Call migrate for removed elements
359             List<UUID> removedElements = findElementsToRemove(acElements, acCopy.getElements());
360             for (var elementId : removedElements) {
361                 var compositionDtoTarget =
362                         new CompositionElementDto(compositionTargetId,
363                                 acCopy.getElements().get(elementId).getDefinition(),
364                                 Map.of(), Map.of(), ElementState.REMOVED);
365                 var instanceDtoTarget =
366                         new InstanceElementDto(acCopy.getInstanceId(), elementId, null, Map.of(),
367                                 Map.of(), ElementState.REMOVED);
368
369                 listener.migrate(messageId, compositionElementMap.get(elementId), compositionDtoTarget,
370                         instanceElementMap.get(elementId), instanceDtoTarget, 0);
371             }
372         }
373     }
374 }