867148d8b2406135451a9f5e6a40251dd849aef0
[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.runtime.instantiation;
23
24 import jakarta.validation.Valid;
25 import jakarta.ws.rs.core.Response.Status;
26 import java.util.List;
27 import java.util.UUID;
28 import java.util.stream.Collectors;
29 import lombok.NonNull;
30 import lombok.RequiredArgsConstructor;
31 import org.onap.policy.clamp.acm.runtime.main.parameters.AcRuntimeParameterGroup;
32 import org.onap.policy.clamp.acm.runtime.supervision.SupervisionAcHandler;
33 import org.onap.policy.clamp.models.acm.concepts.AcTypeState;
34 import org.onap.policy.clamp.models.acm.concepts.AutomationComposition;
35 import org.onap.policy.clamp.models.acm.concepts.AutomationCompositions;
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.NodeTemplateState;
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.rest.instantiation.AcInstanceStateUpdate;
42 import org.onap.policy.clamp.models.acm.messages.rest.instantiation.DeployOrder;
43 import org.onap.policy.clamp.models.acm.messages.rest.instantiation.InstantiationResponse;
44 import org.onap.policy.clamp.models.acm.messages.rest.instantiation.LockOrder;
45 import org.onap.policy.clamp.models.acm.messages.rest.instantiation.SubOrder;
46 import org.onap.policy.clamp.models.acm.persistence.provider.AcDefinitionProvider;
47 import org.onap.policy.clamp.models.acm.persistence.provider.AcInstanceStateResolver;
48 import org.onap.policy.clamp.models.acm.persistence.provider.AutomationCompositionProvider;
49 import org.onap.policy.clamp.models.acm.persistence.provider.ParticipantProvider;
50 import org.onap.policy.clamp.models.acm.utils.AcmUtils;
51 import org.onap.policy.common.parameters.BeanValidationResult;
52 import org.onap.policy.common.parameters.ObjectValidationResult;
53 import org.onap.policy.common.parameters.ValidationStatus;
54 import org.onap.policy.models.base.PfConceptKey;
55 import org.onap.policy.models.base.PfKey;
56 import org.onap.policy.models.base.PfModelRuntimeException;
57 import org.slf4j.Logger;
58 import org.slf4j.LoggerFactory;
59 import org.springframework.stereotype.Service;
60 import org.springframework.transaction.annotation.Transactional;
61
62 /**
63  * This class is dedicated to the Instantiation of Commissioned automation composition.
64  */
65 @Service
66 @Transactional
67 @RequiredArgsConstructor
68 public class AutomationCompositionInstantiationProvider {
69     private static final String DO_NOT_MATCH = " do not match with ";
70     private static final String ELEMENT_ID_NOT_PRESENT = "Element id not present ";
71
72     private static final Logger LOGGER = LoggerFactory.getLogger(AutomationCompositionInstantiationProvider.class);
73
74     private final AutomationCompositionProvider automationCompositionProvider;
75     private final AcDefinitionProvider acDefinitionProvider;
76     private final AcInstanceStateResolver acInstanceStateResolver;
77     private final SupervisionAcHandler supervisionAcHandler;
78     private final ParticipantProvider participantProvider;
79     private final AcRuntimeParameterGroup acRuntimeParameterGroup;
80
81     /**
82      * Create automation composition.
83      *
84      * @param compositionId The UUID of the automation composition definition
85      * @param automationComposition the automation composition
86      * @return the result of the instantiation operation
87      */
88     public InstantiationResponse createAutomationComposition(UUID compositionId,
89             AutomationComposition automationComposition) {
90         if (!compositionId.equals(automationComposition.getCompositionId())) {
91             throw new PfModelRuntimeException(Status.BAD_REQUEST,
92                     automationComposition.getCompositionId() + DO_NOT_MATCH + compositionId);
93         }
94         var checkAutomationCompositionOpt =
95                 automationCompositionProvider.findAutomationComposition(automationComposition.getKey().asIdentifier());
96         if (checkAutomationCompositionOpt.isPresent()) {
97             throw new PfModelRuntimeException(Status.BAD_REQUEST,
98                     automationComposition.getKey().asIdentifier() + " already defined");
99         }
100
101         var validationResult = validateAutomationComposition(automationComposition);
102         if (!validationResult.isValid()) {
103             throw new PfModelRuntimeException(Status.BAD_REQUEST, validationResult.getResult());
104         }
105         automationComposition = automationCompositionProvider.createAutomationComposition(automationComposition);
106
107         return createInstantiationResponse(automationComposition);
108     }
109
110     private InstantiationResponse createInstantiationResponse(AutomationComposition automationComposition) {
111         var response = new InstantiationResponse();
112         response.setInstanceId(automationComposition.getInstanceId());
113         response.setAffectedAutomationComposition(automationComposition.getKey().asIdentifier());
114         return response;
115     }
116
117     /**
118      * Update automation composition.
119      *
120      * @param compositionId The UUID of the automation composition definition
121      * @param automationComposition the automation composition
122      * @return the result of the update
123      */
124     public InstantiationResponse updateAutomationComposition(UUID compositionId,
125             AutomationComposition automationComposition) {
126         var instanceId = automationComposition.getInstanceId();
127         var acToUpdate = automationCompositionProvider.getAutomationComposition(instanceId);
128         if (!compositionId.equals(acToUpdate.getCompositionId())) {
129             throw new PfModelRuntimeException(Status.BAD_REQUEST,
130                     automationComposition.getCompositionId() + DO_NOT_MATCH + compositionId);
131         }
132         if (DeployState.UNDEPLOYED.equals(acToUpdate.getDeployState())) {
133             acToUpdate.setElements(automationComposition.getElements());
134             acToUpdate.setName(automationComposition.getName());
135             acToUpdate.setVersion(automationComposition.getVersion());
136             acToUpdate.setDescription(automationComposition.getDescription());
137             acToUpdate.setDerivedFrom(automationComposition.getDerivedFrom());
138             var validationResult = validateAutomationComposition(acToUpdate);
139             if (!validationResult.isValid()) {
140                 throw new PfModelRuntimeException(Status.BAD_REQUEST, validationResult.getResult());
141             }
142             automationComposition = automationCompositionProvider.updateAutomationComposition(acToUpdate);
143             return createInstantiationResponse(automationComposition);
144
145         }
146
147         if (automationComposition.getRestarting() != null) {
148             throw new PfModelRuntimeException(Status.BAD_REQUEST, "There is a restarting process, Update not allowed");
149         }
150
151         var deployOrder = DeployOrder.UPDATE;
152         var subOrder = SubOrder.NONE;
153
154         if (automationComposition.getCompositionTargetId() != null) {
155
156             if (Boolean.TRUE.equals(automationComposition.getPrecheck())) {
157                 subOrder = SubOrder.MIGRATE_PRECHECK;
158                 deployOrder = DeployOrder.NONE;
159             } else {
160                 deployOrder = DeployOrder.MIGRATE;
161             }
162         }
163         var result = acInstanceStateResolver.resolve(deployOrder, LockOrder.NONE, subOrder,
164                 acToUpdate.getDeployState(), acToUpdate.getLockState(), acToUpdate.getSubState(),
165                 acToUpdate.getStateChangeResult());
166         return switch (result) {
167             case "UPDATE" -> updateDeployedAutomationComposition(automationComposition, acToUpdate);
168
169             case "MIGRATE" -> migrateAutomationComposition(automationComposition, acToUpdate);
170
171             case "MIGRATE_PRECHECK" -> migratePrecheckAc(automationComposition, acToUpdate);
172
173             default -> throw new PfModelRuntimeException(Status.BAD_REQUEST,
174                     "Not allowed to " + deployOrder + " in the state " + acToUpdate.getDeployState());
175         };
176     }
177
178     /**
179      * Update deployed AC Element properties.
180      *
181      * @param automationComposition the automation composition
182      * @param acToBeUpdated the composition to be updated
183      * @return the result of the update
184      */
185     private InstantiationResponse updateDeployedAutomationComposition(
186             AutomationComposition automationComposition, AutomationComposition acToBeUpdated) {
187
188         // Iterate and update the element property values
189         for (var element : automationComposition.getElements().entrySet()) {
190             var elementId = element.getKey();
191             var dbAcElement = acToBeUpdated.getElements().get(elementId);
192             if (dbAcElement == null) {
193                 throw new PfModelRuntimeException(Status.BAD_REQUEST, ELEMENT_ID_NOT_PRESENT + elementId);
194             }
195             AcmUtils.recursiveMerge(dbAcElement.getProperties(), element.getValue().getProperties());
196         }
197
198         var validationResult = validateAutomationComposition(acToBeUpdated);
199         if (!validationResult.isValid()) {
200             throw new PfModelRuntimeException(Status.BAD_REQUEST, validationResult.getResult());
201         }
202         // Publish property update event to the participants
203         supervisionAcHandler.update(acToBeUpdated);
204
205         automationComposition = automationCompositionProvider.updateAutomationComposition(acToBeUpdated);
206         return createInstantiationResponse(automationComposition);
207     }
208
209     private InstantiationResponse migrateAutomationComposition(
210         AutomationComposition automationComposition, AutomationComposition acToBeUpdated) {
211
212         if (!DeployState.DEPLOYED.equals(acToBeUpdated.getDeployState())) {
213             throw new PfModelRuntimeException(Status.BAD_REQUEST,
214                 "Not allowed to migrate in the state " + acToBeUpdated.getDeployState());
215         }
216
217         // Iterate and update the element property values
218         for (var element : automationComposition.getElements().entrySet()) {
219             var elementId = element.getKey();
220             var dbAcElement = acToBeUpdated.getElements().get(elementId);
221             // Add additional elements if present for migration
222             if (dbAcElement == null) {
223                 LOGGER.info("New Ac element {} added in Migration", elementId);
224                 acToBeUpdated.getElements().put(elementId, element.getValue());
225             } else {
226                 AcmUtils.recursiveMerge(dbAcElement.getProperties(), element.getValue().getProperties());
227                 var newDefinition = element.getValue().getDefinition().asConceptKey();
228                 var dbElementDefinition = dbAcElement.getDefinition().asConceptKey();
229                 checkCompatibility(newDefinition, dbElementDefinition, automationComposition.getInstanceId());
230                 dbAcElement.setDefinition(element.getValue().getDefinition());
231             }
232         }
233         // Remove element which is not present in the new Ac instance
234         var elementsRemoved = getElementRemoved(acToBeUpdated, automationComposition);
235         elementsRemoved.forEach(uuid -> acToBeUpdated.getElements().remove(uuid));
236
237         var validationResult =
238                 validateAutomationComposition(acToBeUpdated, automationComposition.getCompositionTargetId());
239         if (!validationResult.isValid()) {
240             throw new PfModelRuntimeException(Status.BAD_REQUEST, validationResult.getResult());
241         }
242         acToBeUpdated.setCompositionTargetId(automationComposition.getCompositionTargetId());
243         var acDefinition = acDefinitionProvider.getAcDefinition(automationComposition.getCompositionTargetId());
244         // Publish migrate event to the participants
245         supervisionAcHandler.migrate(acToBeUpdated, acDefinition.getServiceTemplate());
246
247         var ac = automationCompositionProvider.updateAutomationComposition(acToBeUpdated);
248         elementsRemoved.forEach(automationCompositionProvider::deleteAutomationCompositionElement);
249         return createInstantiationResponse(ac);
250     }
251
252     private List<UUID> getElementRemoved(AutomationComposition acFromDb, AutomationComposition acFromMigration) {
253         return acFromDb.getElements().keySet().stream()
254                 .filter(id -> acFromMigration.getElements().get(id) == null).toList();
255     }
256
257     void checkCompatibility(PfConceptKey newDefinition, PfConceptKey dbElementDefinition,
258                             UUID instanceId) {
259         var compatibility = newDefinition.getCompatibility(dbElementDefinition);
260         if (PfKey.Compatibility.DIFFERENT.equals(compatibility)) {
261             throw new PfModelRuntimeException(Status.BAD_REQUEST,
262                     dbElementDefinition + " is not compatible with " + newDefinition);
263         }
264         if (PfKey.Compatibility.MAJOR.equals(compatibility) || PfKey.Compatibility.MINOR
265                 .equals(compatibility)) {
266             LOGGER.warn("Migrate {}: Version {} has {} compatibility with {} ", instanceId, newDefinition,
267                     compatibility, dbElementDefinition);
268         }
269     }
270
271     private InstantiationResponse migratePrecheckAc(
272             AutomationComposition automationComposition, AutomationComposition acToBeUpdated) {
273
274         acToBeUpdated.setPrecheck(true);
275         var copyAc = new AutomationComposition(acToBeUpdated);
276         // Iterate and update the element property values
277         for (var element : automationComposition.getElements().entrySet()) {
278             var elementId = element.getKey();
279             var copyElement = copyAc.getElements().get(elementId);
280             // Add additional elements if present for migration
281             if (copyElement == null) {
282                 LOGGER.info("New Ac element {} added in Migration", elementId);
283                 copyAc.getElements().put(elementId, element.getValue());
284             } else {
285                 AcmUtils.recursiveMerge(copyElement.getProperties(), element.getValue().getProperties());
286                 var newDefinition = element.getValue().getDefinition().asConceptKey();
287                 var copyElementDefinition = copyElement.getDefinition().asConceptKey();
288                 checkCompatibility(newDefinition, copyElementDefinition, automationComposition.getInstanceId());
289                 copyElement.setDefinition(element.getValue().getDefinition());
290             }
291         }
292         // Remove element which is not present in the new Ac instance
293         var elementsRemoved = getElementRemoved(copyAc, automationComposition);
294         elementsRemoved.forEach(uuid -> copyAc.getElements().remove(uuid));
295
296         var validationResult =
297                 validateAutomationComposition(copyAc, automationComposition.getCompositionTargetId());
298         if (!validationResult.isValid()) {
299             throw new PfModelRuntimeException(Status.BAD_REQUEST, validationResult.getResult());
300         }
301         copyAc.setCompositionTargetId(automationComposition.getCompositionTargetId());
302
303         // Publish migrate event to the participants
304         supervisionAcHandler.migratePrecheck(copyAc);
305
306         AcmUtils.setCascadedState(acToBeUpdated, DeployState.DEPLOYED, LockState.LOCKED,
307             SubState.MIGRATION_PRECHECKING);
308         acToBeUpdated.setStateChangeResult(StateChangeResult.NO_ERROR);
309
310         return createInstantiationResponse(automationCompositionProvider.updateAutomationComposition(acToBeUpdated));
311     }
312
313     private BeanValidationResult validateAutomationComposition(AutomationComposition automationComposition) {
314         return validateAutomationComposition(automationComposition, automationComposition.getCompositionId());
315     }
316
317     /**
318      * Validate AutomationComposition.
319      *
320      * @param automationComposition AutomationComposition to validate
321      * @param compositionId the composition id
322      * @return the result of validation
323      */
324     private BeanValidationResult validateAutomationComposition(AutomationComposition automationComposition,
325             UUID compositionId) {
326
327         var result = new BeanValidationResult("AutomationComposition", automationComposition);
328         var acDefinitionOpt = acDefinitionProvider.findAcDefinition(compositionId);
329         if (acDefinitionOpt.isEmpty()) {
330             result.addResult(new ObjectValidationResult("ServiceTemplate", compositionId, ValidationStatus.INVALID,
331                     "Commissioned automation composition definition not found"));
332             return result;
333         }
334         if (!AcTypeState.PRIMED.equals(acDefinitionOpt.get().getState())) {
335             result.addResult(new ObjectValidationResult("ServiceTemplate.state", acDefinitionOpt.get().getState(),
336                     ValidationStatus.INVALID, "Commissioned automation composition definition not primed"));
337             return result;
338         }
339         if (acDefinitionOpt.get().getRestarting() != null) {
340             result.addResult(
341                     new ObjectValidationResult("ServiceTemplate.restarting", acDefinitionOpt.get().getRestarting(),
342                             ValidationStatus.INVALID, "There is a restarting process in composition"));
343             return result;
344         }
345         var participantIds = acDefinitionOpt.get().getElementStateMap().values().stream()
346                 .map(NodeTemplateState::getParticipantId).collect(Collectors.toSet());
347
348         participantProvider.verifyParticipantState(participantIds);
349
350         result.addResult(AcmUtils.validateAutomationComposition(automationComposition,
351                 acDefinitionOpt.get().getServiceTemplate(),
352                 acRuntimeParameterGroup.getAcmParameters().getToscaCompositionName()));
353
354         result.addResult(automationCompositionProvider.validateElementIds(automationComposition));
355
356         if (result.isValid()) {
357             for (var element : automationComposition.getElements().values()) {
358                 var name = element.getDefinition().getName();
359                 var participantId = acDefinitionOpt.get().getElementStateMap().get(name).getParticipantId();
360                 element.setParticipantId(participantId);
361             }
362         }
363
364         return result;
365     }
366
367     /**
368      * Get Automation Composition.
369      *
370      * @param compositionId The UUID of the automation composition definition
371      * @param instanceId The UUID of the automation composition instance
372      * @return the Automation Composition
373      */
374     @Transactional(readOnly = true)
375     public AutomationComposition getAutomationComposition(@NonNull UUID compositionId, UUID instanceId) {
376         var automationComposition = automationCompositionProvider.getAutomationComposition(instanceId);
377         if (!compositionId.equals(automationComposition.getCompositionId())
378                         && !compositionId.equals(automationComposition.getCompositionTargetId())) {
379             throw new PfModelRuntimeException(Status.BAD_REQUEST,
380                     automationComposition.getCompositionId() + DO_NOT_MATCH + compositionId);
381         }
382         return automationComposition;
383     }
384
385     /**
386      * Delete the automation composition with the given name and version.
387      *
388      * @param compositionId The UUID of the automation composition definition
389      * @param instanceId The UUID of the automation composition instance
390      * @return the result of the deletion
391      */
392     public InstantiationResponse deleteAutomationComposition(UUID compositionId, UUID instanceId) {
393         var automationComposition = automationCompositionProvider.getAutomationComposition(instanceId);
394         if (!compositionId.equals(automationComposition.getCompositionId())) {
395             throw new PfModelRuntimeException(Status.BAD_REQUEST,
396                     automationComposition.getCompositionId() + DO_NOT_MATCH + compositionId);
397         }
398         if (!DeployState.UNDEPLOYED.equals(automationComposition.getDeployState())
399                 && !DeployState.DELETING.equals(automationComposition.getDeployState())) {
400             throw new PfModelRuntimeException(Status.BAD_REQUEST,
401                     "Automation composition state is still " + automationComposition.getDeployState());
402         }
403         if (DeployState.DELETING.equals(automationComposition.getDeployState())
404                 && StateChangeResult.NO_ERROR.equals(automationComposition.getStateChangeResult())) {
405             throw new PfModelRuntimeException(Status.BAD_REQUEST,
406                     "Automation composition state is still " + automationComposition.getDeployState());
407         }
408         if (automationComposition.getRestarting() != null) {
409             throw new PfModelRuntimeException(Status.BAD_REQUEST, "There is a restarting process, Delete not allowed");
410         }
411         var acDefinition = acDefinitionProvider.getAcDefinition(automationComposition.getCompositionId());
412         var participantIds = acDefinition.getElementStateMap().values().stream()
413             .map(NodeTemplateState::getParticipantId).collect(Collectors.toSet());
414         participantProvider.verifyParticipantState(participantIds);
415         supervisionAcHandler.delete(automationComposition, acDefinition);
416         var response = new InstantiationResponse();
417         response.setInstanceId(automationComposition.getInstanceId());
418         response.setAffectedAutomationComposition(automationComposition.getKey().asIdentifier());
419         return response;
420     }
421
422     /**
423      * Get the requested automation compositions.
424      *
425      * @param name the name of the automation composition to get, null for all automation compositions
426      * @param version the version of the automation composition to get, null for all automation compositions
427      * @return the automation compositions
428      */
429     @Transactional(readOnly = true)
430     public AutomationCompositions getAutomationCompositions(UUID compositionId, String name, String version) {
431         var automationCompositions = new AutomationCompositions();
432         automationCompositions.setAutomationCompositionList(
433                 automationCompositionProvider.getAutomationCompositions(compositionId, name, version));
434
435         return automationCompositions;
436     }
437
438     /**
439      * Handle Composition Instance State.
440      *
441      * @param compositionId the compositionId
442      * @param instanceId the instanceId
443      * @param acInstanceStateUpdate the AcInstanceStateUpdate
444      */
445     public void compositionInstanceState(UUID compositionId, UUID instanceId,
446             @Valid AcInstanceStateUpdate acInstanceStateUpdate) {
447         var automationComposition = automationCompositionProvider.getAutomationComposition(instanceId);
448         if (!compositionId.equals(automationComposition.getCompositionId())) {
449             throw new PfModelRuntimeException(Status.BAD_REQUEST,
450                     automationComposition.getCompositionId() + DO_NOT_MATCH + compositionId);
451         }
452         var acDefinition = acDefinitionProvider.getAcDefinition(automationComposition.getCompositionId());
453
454         var participantIds = acDefinition.getElementStateMap().values().stream()
455                 .map(NodeTemplateState::getParticipantId).collect(Collectors.toSet());
456
457         participantProvider.verifyParticipantState(participantIds);
458         var result = acInstanceStateResolver.resolve(acInstanceStateUpdate.getDeployOrder(),
459                 acInstanceStateUpdate.getLockOrder(), acInstanceStateUpdate.getSubOrder(),
460                 automationComposition.getDeployState(), automationComposition.getLockState(),
461                 automationComposition.getSubState(), automationComposition.getStateChangeResult());
462         switch (result) {
463             case "DEPLOY":
464                 supervisionAcHandler.deploy(automationComposition, acDefinition);
465                 break;
466
467             case "UNDEPLOY":
468                 supervisionAcHandler.undeploy(automationComposition, acDefinition);
469                 break;
470
471             case "LOCK":
472                 supervisionAcHandler.lock(automationComposition, acDefinition);
473                 break;
474
475             case "UNLOCK":
476                 supervisionAcHandler.unlock(automationComposition, acDefinition);
477                 break;
478
479             case "PREPARE":
480                 supervisionAcHandler.prepare(automationComposition);
481                 break;
482
483             case "REVIEW":
484                 supervisionAcHandler.review(automationComposition);
485                 break;
486
487             default:
488                 throw new PfModelRuntimeException(Status.BAD_REQUEST, "Not valid " + acInstanceStateUpdate);
489         }
490     }
491 }