6de27f76f12106dbe30c5c6288d7c00f087e3626
[policy/clamp.git] /
1 /*-
2  * ============LICENSE_START=======================================================
3  *  Copyright (C) 2021-2025 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.models.acm.persistence.provider;
22
23 import jakarta.ws.rs.core.Response;
24 import java.util.HashMap;
25 import java.util.List;
26 import java.util.Optional;
27 import java.util.UUID;
28 import lombok.RequiredArgsConstructor;
29 import org.onap.policy.clamp.models.acm.concepts.AcTypeState;
30 import org.onap.policy.clamp.models.acm.concepts.AutomationCompositionDefinition;
31 import org.onap.policy.clamp.models.acm.concepts.NodeTemplateState;
32 import org.onap.policy.clamp.models.acm.concepts.StateChangeResult;
33 import org.onap.policy.clamp.models.acm.document.base.ToscaServiceTemplateValidation;
34 import org.onap.policy.clamp.models.acm.document.concepts.DocToscaServiceTemplate;
35 import org.onap.policy.clamp.models.acm.persistence.concepts.JpaAutomationCompositionDefinition;
36 import org.onap.policy.clamp.models.acm.persistence.concepts.JpaNodeTemplateState;
37 import org.onap.policy.clamp.models.acm.persistence.repository.AutomationCompositionDefinitionRepository;
38 import org.onap.policy.clamp.models.acm.persistence.repository.NodeTemplateStateRepository;
39 import org.onap.policy.clamp.models.acm.utils.AcmUtils;
40 import org.onap.policy.clamp.models.acm.utils.TimestampHelper;
41 import org.onap.policy.common.parameters.BeanValidationResult;
42 import org.onap.policy.models.base.PfModelRuntimeException;
43 import org.onap.policy.models.tosca.authorative.concepts.ToscaServiceTemplate;
44 import org.springframework.data.domain.Example;
45 import org.springframework.stereotype.Service;
46 import org.springframework.transaction.annotation.Isolation;
47 import org.springframework.transaction.annotation.Transactional;
48
49 @Service
50 @Transactional
51 @RequiredArgsConstructor
52 public class AcDefinitionProvider {
53
54     private static final String NAME = "AutomationCompositionDefinition";
55
56     private final AutomationCompositionDefinitionRepository acmDefinitionRepository;
57     private final NodeTemplateStateRepository nodeTemplateStateRepository;
58
59     /**
60      * Create Automation Composition Definition.
61      *
62      * @param serviceTemplate the service template to be created
63      * @return the created ACM Definition
64      */
65     public AutomationCompositionDefinition createAutomationCompositionDefinition(
66             final ToscaServiceTemplate serviceTemplate, final String toscaElementName, String toscaCompositionName) {
67         var acmDefinition = new AutomationCompositionDefinition();
68         var compositionId = UUID.randomUUID();
69         acmDefinition.setCompositionId(compositionId);
70         acmDefinition.setState(AcTypeState.COMMISSIONED);
71         if (serviceTemplate.getMetadata() == null) {
72             serviceTemplate.setMetadata(new HashMap<>());
73         }
74         acmDefinition.setLastMsg(TimestampHelper.now());
75         serviceTemplate.getMetadata().put("compositionId", compositionId);
76         acmDefinition.setServiceTemplate(serviceTemplate);
77         var acElements = AcmUtils.extractAcElementsFromServiceTemplate(serviceTemplate, toscaElementName);
78         if (acElements.isEmpty()) {
79             throw new PfModelRuntimeException(Response.Status.BAD_REQUEST,
80                     "NodeTemplate with element type " + toscaElementName + " must exist!");
81         }
82         acmDefinition.setElementStateMap(AcmUtils.createElementStateMap(acElements, AcTypeState.COMMISSIONED));
83         var jpaAcmDefinition = ProviderUtils.getJpaAndValidate(acmDefinition, JpaAutomationCompositionDefinition::new,
84             acmDefinition.getClass().getSimpleName());
85         var validationResult = new BeanValidationResult(acmDefinition.getClass().getSimpleName(), acmDefinition);
86         ToscaServiceTemplateValidation.validate(validationResult, jpaAcmDefinition.getServiceTemplate(),
87                 toscaCompositionName);
88         if (! validationResult.isValid()) {
89             throw new PfModelRuntimeException(Response.Status.BAD_REQUEST, validationResult.getResult());
90         }
91         var result = acmDefinitionRepository.save(jpaAcmDefinition);
92
93         return result.toAuthorative();
94     }
95
96     /**
97      * Update a commissioned ServiceTemplate.
98      *
99      * @param compositionId The UUID of the automation composition definition to delete
100      * @param serviceTemplate the service template to be created
101      */
102     public void updateServiceTemplate(UUID compositionId, ToscaServiceTemplate serviceTemplate, String toscaElementName,
103                                       String toscaCompositionName) {
104         var acmDefinition = new AutomationCompositionDefinition();
105         acmDefinition.setCompositionId(compositionId);
106         acmDefinition.setState(AcTypeState.COMMISSIONED);
107         acmDefinition.setLastMsg(TimestampHelper.now());
108         acmDefinition.setServiceTemplate(serviceTemplate);
109         var acElements =
110                 AcmUtils.extractAcElementsFromServiceTemplate(serviceTemplate, toscaElementName);
111         if (acElements.isEmpty()) {
112             throw new PfModelRuntimeException(Response.Status.BAD_REQUEST,
113                     "NodeTemplate with element type " + toscaElementName + " must exist!");
114         }
115         acmDefinition.setElementStateMap(AcmUtils.createElementStateMap(acElements, AcTypeState.COMMISSIONED));
116         updateAcDefinition(acmDefinition, toscaCompositionName);
117     }
118
119     /**
120      * Update the AutomationCompositionDefinition.
121      *
122      * @param acDefinition the AutomationCompositionDefinition to be updated
123      */
124     public void updateAcDefinition(AutomationCompositionDefinition acDefinition, String toscaCompositionName) {
125         var jpaAcmDefinition = ProviderUtils.getJpaAndValidate(acDefinition, JpaAutomationCompositionDefinition::new,
126                 NAME);
127         var validationResult = new BeanValidationResult(NAME, acDefinition);
128         ToscaServiceTemplateValidation.validate(validationResult, jpaAcmDefinition.getServiceTemplate(),
129                 toscaCompositionName);
130         if (! validationResult.isValid()) {
131             throw new PfModelRuntimeException(Response.Status.BAD_REQUEST, validationResult.getResult());
132         }
133         acmDefinitionRepository.save(jpaAcmDefinition);
134         acmDefinitionRepository.flush();
135     }
136
137     /**
138      * Update Ac Definition with unchanged service template.
139      *
140      * @param acDefinition the AutomationCompositionDefinition to be updated
141      */
142     public void updateAcDefinitionState(AutomationCompositionDefinition acDefinition) {
143         var jpaAcmDefinition = ProviderUtils.getJpaAndValidate(acDefinition, JpaAutomationCompositionDefinition::new,
144                 NAME);
145         acmDefinitionRepository.save(jpaAcmDefinition);
146         acmDefinitionRepository.flush();
147     }
148
149     /**
150      * Update Ac Definition AcTypeState, StateChangeResult and restarting.
151      *
152      * @param compositionId The UUID of the automation composition definition to update
153      * @param state the AcTypeState
154      * @param stateChangeResult the StateChangeResult
155      */
156     public void updateAcDefinitionState(UUID compositionId, AcTypeState state, StateChangeResult stateChangeResult) {
157         var jpaUpdate = acmDefinitionRepository.findById(compositionId.toString());
158         if (jpaUpdate.isEmpty()) {
159             String errorMessage = "update of Automation Composition Definition \"" + compositionId
160                 + "\" failed, Automation Composition Definition does not exist";
161             throw new PfModelRuntimeException(Response.Status.NOT_FOUND, errorMessage);
162         }
163         var acDefinition = jpaUpdate.get();
164         acDefinition.setState(state);
165         acDefinition.setStateChangeResult(stateChangeResult);
166         acmDefinitionRepository.save(acDefinition);
167         acmDefinitionRepository.flush();
168     }
169
170     /**
171      * Update Ac DefinitionElement.
172      *
173      * @param nodeTemplateState the NodeTemplateState
174      * @param compositionId The UUID of the automation composition definition
175      */
176     public void updateAcDefinitionElement(NodeTemplateState nodeTemplateState, UUID compositionId) {
177         var jpaNodeTemplateState = new JpaNodeTemplateState(
178             nodeTemplateState.getNodeTemplateStateId().toString(), compositionId.toString());
179         jpaNodeTemplateState.fromAuthorative(nodeTemplateState);
180         nodeTemplateStateRepository.save(jpaNodeTemplateState);
181     }
182
183     /**
184      * Delete Automation Composition Definition.
185      *
186      * @param compositionId The UUID of the automation composition definition to delete
187      * @return the TOSCA service template that was deleted
188      */
189     public ToscaServiceTemplate deleteAcDefintion(UUID compositionId) {
190         var jpaDelete = acmDefinitionRepository.findById(compositionId.toString());
191         if (jpaDelete.isEmpty()) {
192             String errorMessage = "delete of Automation Composition Definition \"" + compositionId
193                     + "\" failed, Automation Composition Definition does not exist";
194             throw new PfModelRuntimeException(Response.Status.NOT_FOUND, errorMessage);
195         }
196
197         var item = jpaDelete.get().getServiceTemplate();
198         acmDefinitionRepository.deleteById(compositionId.toString());
199         return item.toAuthorative();
200     }
201
202     /**
203      * Get the requested automation composition definitions.
204      *
205      * @param compositionId The UUID of the automation composition definition to delete
206      * @return the automation composition definition
207      */
208     @Transactional(readOnly = true)
209     public AutomationCompositionDefinition getAcDefinition(UUID compositionId) {
210         var jpaGet = acmDefinitionRepository.findById(compositionId.toString());
211         if (jpaGet.isEmpty()) {
212             String errorMessage =
213                     "Get serviceTemplate \"" + compositionId + "\" failed, serviceTemplate does not exist";
214             throw new PfModelRuntimeException(Response.Status.NOT_FOUND, errorMessage);
215         }
216         return jpaGet.get().toAuthorative();
217     }
218
219     /**
220      * Get the requested automation composition definition.
221      *
222      * @param compositionId The UUID of the automation composition definition to delete
223      * @return the automation composition definition
224      */
225     @Transactional(readOnly = true, isolation = Isolation.READ_UNCOMMITTED)
226     public Optional<AutomationCompositionDefinition> findAcDefinition(UUID compositionId) {
227         var jpaGet = acmDefinitionRepository.findById(compositionId.toString());
228         return jpaGet.stream().map(JpaAutomationCompositionDefinition::toAuthorative).findFirst();
229     }
230
231     /**
232      * Get Automation Composition Definitions in transition.
233      *
234      * @return the Automation Composition Definitions found
235      */
236     @Transactional(readOnly = true)
237     public List<AutomationCompositionDefinition> getAllAcDefinitionsInTransition() {
238         var jpaList = acmDefinitionRepository.findByStateIn(List.of(AcTypeState.PRIMING, AcTypeState.DEPRIMING));
239         return ProviderUtils.asEntityList(jpaList);
240     }
241
242     /**
243      * Get service templates.
244      *
245      * @param name the name of the topology template to get, set to null to get all service templates
246      * @param version the version of the service template to get, set to null to get all service templates
247      * @return the topology templates found
248      */
249     @Transactional(readOnly = true)
250     public List<ToscaServiceTemplate> getServiceTemplateList(final String name, final String version) {
251         List<JpaAutomationCompositionDefinition> jpaList = null;
252         if (name != null || version != null) {
253             var entity = new JpaAutomationCompositionDefinition();
254             entity.setName(name);
255             entity.setVersion(version);
256             var example = Example.of(entity);
257             jpaList = acmDefinitionRepository.findAll(example);
258         } else {
259             jpaList = acmDefinitionRepository.findAll();
260         }
261
262         return jpaList.stream().map(JpaAutomationCompositionDefinition::getServiceTemplate)
263                 .map(DocToscaServiceTemplate::toAuthorative).toList();
264     }
265 }