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