8be12960bf6564cbb154951b78a106abf1926a5f
[policy/clamp.git] /
1 /*-
2  * ============LICENSE_START=======================================================
3  * Copyright (C) 2021-2024 Nordix Foundation.
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.ArrayList;
28 import java.util.List;
29 import java.util.Optional;
30 import java.util.UUID;
31 import lombok.AllArgsConstructor;
32 import lombok.NonNull;
33 import org.onap.policy.clamp.models.acm.concepts.AutomationComposition;
34 import org.onap.policy.clamp.models.acm.concepts.AutomationCompositionElement;
35 import org.onap.policy.clamp.models.acm.concepts.AutomationCompositionInfo;
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.persistence.concepts.JpaAutomationComposition;
39 import org.onap.policy.clamp.models.acm.persistence.concepts.JpaAutomationCompositionElement;
40 import org.onap.policy.clamp.models.acm.persistence.repository.AutomationCompositionElementRepository;
41 import org.onap.policy.clamp.models.acm.persistence.repository.AutomationCompositionRepository;
42 import org.onap.policy.clamp.models.acm.utils.AcmUtils;
43 import org.onap.policy.common.parameters.BeanValidationResult;
44 import org.onap.policy.common.parameters.ValidationStatus;
45 import org.onap.policy.models.base.PfModelRuntimeException;
46 import org.onap.policy.models.tosca.authorative.concepts.ToscaConceptIdentifier;
47 import org.springframework.data.domain.Example;
48 import org.springframework.stereotype.Service;
49 import org.springframework.transaction.annotation.Isolation;
50 import org.springframework.transaction.annotation.Transactional;
51
52 /**
53  * This class provides information on automation composition concepts in the database to callers.
54  */
55 @Service
56 @Transactional
57 @AllArgsConstructor
58 public class AutomationCompositionProvider {
59
60     private final AutomationCompositionRepository automationCompositionRepository;
61     private final AutomationCompositionElementRepository acElementRepository;
62
63     /**
64      * Get automation composition.
65      *
66      * @param instanceId the ID of the automation composition to get
67      * @return the automation composition found
68      */
69     @Transactional(readOnly = true)
70     public AutomationComposition getAutomationComposition(final UUID instanceId) {
71         var result = automationCompositionRepository.findById(instanceId.toString());
72         if (result.isEmpty()) {
73             throw new PfModelRuntimeException(Status.NOT_FOUND, "AutomationComposition not found");
74         }
75         return result.get().toAuthorative();
76     }
77
78     /**
79      * Find automation composition.
80      *
81      * @param instanceId the ID of the automation composition to get
82      * @return the automation composition found
83      */
84     @Transactional(readOnly = true, isolation = Isolation.READ_UNCOMMITTED)
85     public Optional<AutomationComposition> findAutomationComposition(final UUID instanceId) {
86         var result = automationCompositionRepository.findById(instanceId.toString());
87         return result.stream().map(JpaAutomationComposition::toAuthorative).findFirst();
88     }
89
90     /**
91      * Find automation composition by automationCompositionId.
92      *
93      * @param automationCompositionId the ID of the automation composition to get
94      * @return the automation composition found
95      */
96     @Transactional(readOnly = true)
97     public Optional<AutomationComposition> findAutomationComposition(
98             final ToscaConceptIdentifier automationCompositionId) {
99         return automationCompositionRepository
100                 .findOne(createExample(null, automationCompositionId.getName(), automationCompositionId.getVersion()))
101                 .map(JpaAutomationComposition::toAuthorative);
102     }
103
104     /**
105      * Create automation composition.
106      *
107      * @param automationComposition the automation composition to create
108      * @return the create automation composition
109      */
110     public AutomationComposition createAutomationComposition(final AutomationComposition automationComposition) {
111         automationComposition.setInstanceId(UUID.randomUUID());
112         AcmUtils.setCascadedState(automationComposition, DeployState.UNDEPLOYED, LockState.NONE);
113         var result = automationCompositionRepository.save(ProviderUtils.getJpaAndValidate(automationComposition,
114                 JpaAutomationComposition::new, "automation composition"));
115
116         // Return the saved automation composition
117         return result.toAuthorative();
118     }
119
120     /**
121      * Update automation composition.
122      *
123      * @param automationComposition the automation composition to update
124      * @return the updated automation composition
125      */
126     public AutomationComposition updateAutomationComposition(
127             @NonNull final AutomationComposition automationComposition) {
128         var result = automationCompositionRepository.save(ProviderUtils.getJpaAndValidate(automationComposition,
129                 JpaAutomationComposition::new, "automation composition"));
130         automationCompositionRepository.flush();
131         // Return the saved automation composition
132         return result.toAuthorative();
133     }
134
135     /**
136      * Get all automation compositions by compositionId.
137      *
138      * @param compositionId the compositionId of the automation composition definition
139      * @return all automation compositions found
140      */
141     @Transactional(readOnly = true)
142     public List<AutomationComposition> getAcInstancesByCompositionId(UUID compositionId) {
143         return ProviderUtils
144                 .asEntityList(automationCompositionRepository.findByCompositionId(compositionId.toString()));
145     }
146
147     /**
148      * Get all automation compositions in transition..
149      *
150      * @return all automation compositions found
151      */
152     @Transactional(readOnly = true)
153     public List<AutomationComposition> getAcInstancesInTransition() {
154         var jpaList = automationCompositionRepository.findByDeployStateIn(List.of(DeployState.DEPLOYING,
155             DeployState.UNDEPLOYING, DeployState.DELETING, DeployState.UPDATING, DeployState.MIGRATING));
156         jpaList.addAll(automationCompositionRepository.findByLockStateIn(
157             List.of(LockState.LOCKING, LockState.UNLOCKING)));
158         return ProviderUtils.asEntityList(jpaList);
159     }
160
161     /**
162      * Get automation compositions.
163      *
164      * @param name the name of the automation composition to get, null to get all automation compositions
165      * @param version the version of the automation composition to get, null to get all automation compositions
166      * @return the automation compositions found
167      */
168     @Transactional(readOnly = true)
169     public List<AutomationComposition> getAutomationCompositions(final UUID compositionId, final String name,
170             final String version) {
171
172         return ProviderUtils
173                 .asEntityList(automationCompositionRepository.findAll(createExample(compositionId, name, version)));
174     }
175
176     private Example<JpaAutomationComposition> createExample(final UUID compositionId, final String name,
177             final String version) {
178         var example = new JpaAutomationComposition();
179         example.setCompositionId(compositionId != null ? compositionId.toString() : null);
180         example.setName(name);
181         example.setVersion(version);
182         example.setInstanceId(null);
183         example.setElements(null);
184         example.setDeployState(null);
185         example.setLockState(null);
186
187         return Example.of(example);
188     }
189
190     /**
191      * Delete a automation composition.
192      *
193      * @param instanceId the ID of the automation composition to get
194      * @return the automation composition deleted
195      */
196     public AutomationComposition deleteAutomationComposition(@NonNull final UUID instanceId) {
197         var jpaDeleteAutomationComposition = automationCompositionRepository.findById(instanceId.toString());
198         if (jpaDeleteAutomationComposition.isEmpty()) {
199             var errorMessage = "delete of automation composition \"" + instanceId
200                     + "\" failed, automation composition does not exist";
201             throw new PfModelRuntimeException(Response.Status.NOT_FOUND, errorMessage);
202         }
203
204         automationCompositionRepository.deleteById(instanceId.toString());
205
206         return jpaDeleteAutomationComposition.get().toAuthorative();
207     }
208
209     /**
210      * Upgrade States.
211      *
212      * @param automationCompositionInfoList list of AutomationCompositionInfo
213      */
214     public void upgradeStates(@NonNull final List<AutomationCompositionInfo> automationCompositionInfoList) {
215         if (automationCompositionInfoList.isEmpty()) {
216             return;
217         }
218         List<JpaAutomationCompositionElement> jpaList = new ArrayList<>();
219         for (var acInstance : automationCompositionInfoList) {
220             for (var element : acInstance.getElements()) {
221                 var jpa = acElementRepository.getReferenceById(element.getAutomationCompositionElementId().toString());
222                 jpa.setUseState(element.getUseState());
223                 jpa.setOperationalState(element.getOperationalState());
224                 jpa.setOutProperties(element.getOutProperties());
225                 jpaList.add(jpa);
226             }
227         }
228         acElementRepository.saveAll(jpaList);
229     }
230
231     /**
232      * Update AutomationCompositionElement.
233      *
234      * @param element the AutomationCompositionElement
235      * @param instanceId the instance Id
236      */
237     public void updateAutomationCompositionElement(@NonNull final AutomationCompositionElement element,
238                 @NonNull final UUID instanceId) {
239         var jpaAcElement = new JpaAutomationCompositionElement(element.getId().toString(), instanceId.toString());
240         jpaAcElement.fromAuthorative(element);
241         ProviderUtils.validate(element, jpaAcElement, "AutomationCompositionElement");
242         acElementRepository.save(jpaAcElement);
243     }
244
245     /**
246      * Validate ElementIds.
247      *
248      * @param automationComposition the AutomationComposition
249      * @return the BeanValidationResult
250      */
251     public BeanValidationResult validateElementIds(final AutomationComposition automationComposition) {
252         var result = new BeanValidationResult(
253             "UUID elements " + automationComposition.getName(), automationComposition);
254
255         var ids = automationComposition
256             .getElements().values().stream().map(AutomationCompositionElement::getId).toList();
257         var elements = acElementRepository.findAllById(ids.stream().map(UUID::toString).toList());
258         if (automationComposition.getInstanceId() == null) {
259             for (var element : elements) {
260                 result.addResult(
261                     element.getDescription(), element.getElementId(), ValidationStatus.INVALID, "UUID already used");
262             }
263         } else {
264             var instanceId = automationComposition.getInstanceId().toString();
265             for (var element : elements) {
266                 if (!instanceId.equals(element.getInstanceId())) {
267                     result.addResult(
268                         element.getDescription(), element.getElementId(), ValidationStatus.INVALID,
269                         "UUID already used");
270                 }
271             }
272         }
273         return result;
274     }
275 }