d12d78d16377694d5f629327dcacca173d4ff945
[policy/clamp.git] /
1 /*-
2  * ============LICENSE_START=======================================================
3  * Copyright (C) 2021-2025 OpenInfra Foundation Europe. All rights reserved.
4  * ================================================================================
5  * Modifications Copyright (C) 2021 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  *
19  * SPDX-License-Identifier: Apache-2.0
20  * ============LICENSE_END=========================================================
21  */
22
23 package org.onap.policy.clamp.models.acm.persistence.provider;
24
25 import jakarta.ws.rs.core.Response;
26 import jakarta.ws.rs.core.Response.Status;
27 import java.util.List;
28 import java.util.Optional;
29 import java.util.Set;
30 import java.util.UUID;
31 import java.util.stream.Collectors;
32 import lombok.AllArgsConstructor;
33 import lombok.NonNull;
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.AutomationCompositionRollback;
37 import org.onap.policy.clamp.models.acm.concepts.DeployState;
38 import org.onap.policy.clamp.models.acm.concepts.LockState;
39 import org.onap.policy.clamp.models.acm.concepts.SubState;
40 import org.onap.policy.clamp.models.acm.persistence.concepts.JpaAutomationComposition;
41 import org.onap.policy.clamp.models.acm.persistence.concepts.JpaAutomationCompositionRollback;
42 import org.onap.policy.clamp.models.acm.persistence.repository.AutomationCompositionElementRepository;
43 import org.onap.policy.clamp.models.acm.persistence.repository.AutomationCompositionRepository;
44 import org.onap.policy.clamp.models.acm.persistence.repository.AutomationCompositionRollbackRepository;
45 import org.onap.policy.clamp.models.acm.utils.AcmUtils;
46 import org.onap.policy.common.parameters.BeanValidationResult;
47 import org.onap.policy.common.parameters.ValidationStatus;
48 import org.onap.policy.models.base.PfModelRuntimeException;
49 import org.onap.policy.models.tosca.authorative.concepts.ToscaConceptIdentifier;
50 import org.springframework.data.domain.Example;
51 import org.springframework.data.domain.Pageable;
52 import org.springframework.stereotype.Service;
53 import org.springframework.transaction.annotation.Isolation;
54 import org.springframework.transaction.annotation.Transactional;
55
56 /**
57  * This class provides information on automation composition concepts in the database to callers.
58  */
59 @Service
60 @Transactional
61 @AllArgsConstructor
62 public class AutomationCompositionProvider {
63
64     private final AutomationCompositionRepository automationCompositionRepository;
65     private final AutomationCompositionElementRepository acElementRepository;
66     private final AutomationCompositionRollbackRepository acRollbackRepository;
67
68     /**
69      * Get automation composition.
70      *
71      * @param instanceId the ID of the automation composition to get
72      * @return the automation composition found
73      */
74     @Transactional(readOnly = true)
75     public AutomationComposition getAutomationComposition(final UUID instanceId) {
76         var result = automationCompositionRepository.findById(instanceId.toString());
77         if (result.isEmpty()) {
78             throw new PfModelRuntimeException(Status.NOT_FOUND, "AutomationComposition not found");
79         }
80         return result.get().toAuthorative();
81     }
82
83     /**
84      * Find automation composition.
85      *
86      * @param instanceId the ID of the automation composition to get
87      * @return the automation composition found
88      */
89     @Transactional(readOnly = true, isolation = Isolation.READ_UNCOMMITTED)
90     public Optional<AutomationComposition> findAutomationComposition(final UUID instanceId) {
91         var result = automationCompositionRepository.findById(instanceId.toString());
92         return result.stream().map(JpaAutomationComposition::toAuthorative).findFirst();
93     }
94
95     /**
96      * Find automation composition by automationCompositionId.
97      *
98      * @param automationCompositionId the ID of the automation composition to get
99      * @return the automation composition found
100      */
101     @Transactional(readOnly = true)
102     public Optional<AutomationComposition> findAutomationComposition(
103         final ToscaConceptIdentifier automationCompositionId) {
104         return automationCompositionRepository
105             .findOne(createExample(null, automationCompositionId.getName(), automationCompositionId.getVersion()))
106             .map(JpaAutomationComposition::toAuthorative);
107     }
108
109     /**
110      * Create automation composition.
111      *
112      * @param automationComposition the automation composition to create
113      * @return the created automation composition
114      */
115     public AutomationComposition createAutomationComposition(final AutomationComposition automationComposition) {
116         automationComposition.setInstanceId(UUID.randomUUID());
117         AcmUtils.setCascadedState(automationComposition, DeployState.UNDEPLOYED, LockState.NONE);
118         var result = automationCompositionRepository.save(ProviderUtils.getJpaAndValidate(automationComposition,
119             JpaAutomationComposition::new, "automation composition"));
120
121         // Return the saved automation composition
122         return result.toAuthorative();
123     }
124
125     /**
126      * Update automation composition.
127      *
128      * @param automationComposition the automation composition to update
129      * @return the updated automation composition
130      */
131     public AutomationComposition updateAutomationComposition(
132         @NonNull final AutomationComposition automationComposition) {
133         var result = automationCompositionRepository.save(ProviderUtils.getJpaAndValidate(automationComposition,
134             JpaAutomationComposition::new, "automation composition"));
135         automationCompositionRepository.flush();
136         // Return the saved automation composition
137         return result.toAuthorative();
138     }
139
140     /**
141      * Get all automation compositions by compositionId.
142      *
143      * @param compositionId the compositionId of the automation composition definition
144      * @return all automation compositions found
145      */
146     @Transactional(readOnly = true)
147     public List<AutomationComposition> getAcInstancesByCompositionId(UUID compositionId) {
148         return ProviderUtils
149             .asEntityList(automationCompositionRepository.findByCompositionId(compositionId.toString()));
150     }
151
152     /**
153      * Get all automation compositions in transition.
154      *
155      * @return all automation compositions found
156      */
157     @Transactional(readOnly = true)
158     public Set<UUID> getAcInstancesInTransition() {
159         var jpaList = automationCompositionRepository.findByDeployStateIn(List.of(DeployState.DEPLOYING,
160             DeployState.UNDEPLOYING, DeployState.DELETING, DeployState.UPDATING, DeployState.MIGRATING,
161             DeployState.MIGRATION_REVERTING));
162         jpaList.addAll(automationCompositionRepository.findByLockStateIn(
163             List.of(LockState.LOCKING, LockState.UNLOCKING)));
164         jpaList.addAll(automationCompositionRepository.findBySubStateIn(
165             List.of(SubState.PREPARING, SubState.MIGRATION_PRECHECKING, SubState.REVIEWING)));
166         return jpaList.stream().map(JpaAutomationComposition::getInstanceId)
167             .map(UUID::fromString).collect(Collectors.toSet());
168     }
169
170     /**
171      * Get automation compositions.
172      *
173      * @param name     the name of the automation composition to get, null to get all automation compositions
174      * @param version  the version of the automation composition to get, null to get all automation compositions
175      * @param pageable the Pageable
176      * @return the automation compositions found
177      */
178     @Transactional(readOnly = true)
179     public List<AutomationComposition> getAutomationCompositions(@NonNull final UUID compositionId, final String name,
180                                                                  final String version,
181                                                                  @NonNull final Pageable pageable) {
182         return ProviderUtils.asEntityList(automationCompositionRepository
183             .findAll(createExample(compositionId, name, version), pageable).toList());
184     }
185
186     private Example<JpaAutomationComposition> createExample(final UUID compositionId, final String name,
187                                                             final String version) {
188         var example = new JpaAutomationComposition();
189         example.setCompositionId(compositionId != null ? compositionId.toString() : null);
190         example.setName(name);
191         example.setVersion(version);
192         example.setInstanceId(null);
193         example.setElements(null);
194         example.setDeployState(null);
195         example.setLockState(null);
196
197         return Example.of(example);
198     }
199
200     /**
201      * Delete a automation composition.
202      *
203      * @param instanceId the ID of the automation composition to get
204      * @return the automation composition deleted
205      */
206     public AutomationComposition deleteAutomationComposition(@NonNull final UUID instanceId) {
207         var jpaDeleteAutomationComposition = automationCompositionRepository.findById(instanceId.toString());
208         if (jpaDeleteAutomationComposition.isEmpty()) {
209             var errorMessage = "delete of automation composition \"" + instanceId
210                 + "\" failed, automation composition does not exist";
211             throw new PfModelRuntimeException(Response.Status.NOT_FOUND, errorMessage);
212         }
213
214         if (acRollbackRepository.existsById(instanceId.toString())) {
215             acRollbackRepository.deleteById(instanceId.toString());
216         }
217         automationCompositionRepository.deleteById(instanceId.toString());
218
219         return jpaDeleteAutomationComposition.get().toAuthorative();
220     }
221
222     /**
223      * Delete AutomationCompositionElement.
224      *
225      * @param elementId the AutomationCompositionElement Id
226      */
227     public void deleteAutomationCompositionElement(@NonNull final UUID elementId) {
228         acElementRepository.deleteById(elementId.toString());
229     }
230
231     /**
232      * Validate ElementIds.
233      *
234      * @param automationComposition the AutomationComposition
235      * @return the BeanValidationResult
236      */
237     public BeanValidationResult validateElementIds(final AutomationComposition automationComposition) {
238         var result = new BeanValidationResult(
239             "UUID elements " + automationComposition.getName(), automationComposition);
240
241         var ids = automationComposition
242             .getElements().values().stream().map(AutomationCompositionElement::getId).toList();
243         var elements = acElementRepository.findAllById(ids.stream().map(UUID::toString).toList());
244         if (automationComposition.getInstanceId() == null) {
245             for (var element : elements) {
246                 result.addResult(
247                     element.getDescription(), element.getElementId(), ValidationStatus.INVALID, "UUID already used");
248             }
249         } else {
250             var instanceId = automationComposition.getInstanceId().toString();
251             for (var element : elements) {
252                 if (!instanceId.equals(element.getInstanceId())) {
253                     result.addResult(
254                         element.getDescription(), element.getElementId(), ValidationStatus.INVALID,
255                         "UUID already used");
256                 }
257             }
258         }
259         return result;
260     }
261
262     /**
263      * Save a copy of an automation composition to the copy table in case of a rollback.
264      *
265      * @param automationComposition the composition to be copied
266      */
267     public void copyAcElementsBeforeUpdate(AutomationComposition automationComposition) {
268         var copy = new AutomationCompositionRollback(automationComposition);
269         var jpaCopy = new JpaAutomationCompositionRollback(copy);
270         acRollbackRepository.save(jpaCopy);
271         acRollbackRepository.flush();
272     }
273
274     /**
275      * Get the copied automation composition from the RollbackRepository.
276      *
277      * @param instanceId the id of the ac instance
278      * @return the acRollback object
279      */
280     public AutomationCompositionRollback getAutomationCompositionRollback(UUID instanceId) {
281         var result = acRollbackRepository.findById(instanceId.toString());
282         if (result.isEmpty()) {
283             throw new PfModelRuntimeException(Status.NOT_FOUND, "Instance not found for rollback");
284         }
285         return result.get().toAuthorative();
286     }
287 }