b4eec379005877db5ea332e6eda619947781c29f
[policy/api.git] / main / src / main / java / org / onap / policy / api / main / service / NodeTemplateService.java
1 /*-
2  * ============LICENSE_START=======================================================
3  *  Copyright (C) 2022 Nordix Foundation. 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.api.main.service;
22
23 import java.util.Optional;
24 import javax.ws.rs.core.Response;
25 import lombok.NonNull;
26 import lombok.RequiredArgsConstructor;
27 import org.onap.policy.api.main.repository.NodeTemplateRepository;
28 import org.onap.policy.api.main.repository.NodeTypeRepository;
29 import org.onap.policy.models.base.PfConceptKey;
30 import org.onap.policy.models.base.PfModelException;
31 import org.onap.policy.models.base.PfModelRuntimeException;
32 import org.onap.policy.models.tosca.simple.concepts.JpaToscaNodeTemplate;
33 import org.onap.policy.models.tosca.simple.concepts.JpaToscaNodeTemplates;
34 import org.onap.policy.models.tosca.simple.concepts.JpaToscaNodeType;
35 import org.onap.policy.models.tosca.simple.concepts.JpaToscaPolicy;
36 import org.onap.policy.models.tosca.simple.concepts.JpaToscaServiceTemplate;
37 import org.onap.policy.models.tosca.utils.ToscaUtils;
38 import org.slf4j.Logger;
39 import org.slf4j.LoggerFactory;
40 import org.springframework.stereotype.Service;
41 import org.springframework.transaction.annotation.Transactional;
42
43 @Service
44 @Transactional
45 @RequiredArgsConstructor
46 public class NodeTemplateService {
47
48     private static final Logger LOGGER = LoggerFactory.getLogger(NodeTemplateService.class);
49
50     private final NodeTemplateRepository nodeTemplateRepository;
51     private final NodeTypeRepository nodeTypeRepository;
52
53     /**
54      * Delete the specified node template.
55      *
56      * @param nodeTemplateKey the node template key containing name and version
57      */
58     public void deleteNodeTemplate(final PfConceptKey nodeTemplateKey) {
59         nodeTemplateRepository.deleteById(nodeTemplateKey);
60     }
61
62
63     /**
64      * Update the specified tosca node template.
65      * @param incomingServiceTemplate incoming service template
66      */
67     public void updateToscaNodeTemplates(@NonNull final JpaToscaServiceTemplate incomingServiceTemplate)
68         throws PfModelRuntimeException, PfModelException {
69         for (JpaToscaNodeTemplate nodeTemplate : incomingServiceTemplate.getTopologyTemplate().getNodeTemplates()
70             .getAll(null)) {
71             //verify if the node template is referenced in the metadata of created policies
72             assertNodeTemplateNotUsedInPolicy(nodeTemplate.getName(), nodeTemplate.getVersion(),
73                 incomingServiceTemplate);
74             verifyNodeTypeInDbTemplate(nodeTemplate);
75             Optional<JpaToscaNodeTemplate> dbNodeTemplate = nodeTemplateRepository.findById(nodeTemplate.getKey());
76             if (dbNodeTemplate.isPresent()) {
77                 nodeTemplateRepository.save(nodeTemplate);
78             } else {
79                 throw new PfModelRuntimeException(Response.Status.NOT_ACCEPTABLE, "node template "
80                     + nodeTemplate.getName() + " version " + nodeTemplate.getVersion() + " does not exist in database");
81             }
82         }
83
84         // Return the service template with updated node templates
85         var updatedNodeTemplates = new JpaToscaNodeTemplates();
86         updatedNodeTemplates.setKey(incomingServiceTemplate.getTopologyTemplate().getNodeTemplates().getKey());
87
88         for (PfConceptKey key : incomingServiceTemplate.getTopologyTemplate().getNodeTemplates()
89             .getConceptMap().keySet()) {
90             Optional<JpaToscaNodeTemplate> jpaNodeTemplate = nodeTemplateRepository.findById(key);
91             jpaNodeTemplate.ifPresent(
92                 jpaToscaNodeTemplate -> updatedNodeTemplates.getConceptMap().put(key, jpaToscaNodeTemplate));
93         }
94         incomingServiceTemplate.getTopologyTemplate().setNodeTemplates(updatedNodeTemplates);
95
96     }
97
98
99     /**
100      * Verify the node type for a toscaNodeTemplate .
101      *
102      * @param toscaNodeTemplate the toscaNodeTemplate to check the toscaNodeTemplate type for
103      */
104     public void verifyNodeTypeInDbTemplate(final JpaToscaNodeTemplate toscaNodeTemplate) throws
105         PfModelException {
106         PfConceptKey nodeTypeKey = toscaNodeTemplate.getType();
107
108         Optional<JpaToscaNodeType> nodeType = nodeTypeRepository.findById(nodeTypeKey);
109
110         if (nodeType.isEmpty()) {
111             String errorMessage =
112                 "NODE_TYPE " + nodeTypeKey + " for toscaNodeTemplate " + toscaNodeTemplate.getId()
113                     + " does not exist";
114             throw new PfModelException(Response.Status.NOT_ACCEPTABLE, errorMessage);
115         }
116     }
117
118     /**
119      * Assert that the node template is not referenced in any Tosca policy.
120      *
121      * @param name the name of node template
122      * @param version the version of node template
123      * @throws PfModelException if node template referenced in a policy
124      */
125     public void assertNodeTemplateNotUsedInPolicy(String name, String version, JpaToscaServiceTemplate dbTemplate)
126         throws PfModelException {
127         try {
128             //Retrieve all the policies from db, return if policies doesn't exist
129             ToscaUtils.assertPoliciesExist(dbTemplate);
130         } catch (PfModelRuntimeException e) {
131             LOGGER.debug("Could not verify the node template reference in created policies ", e);
132             return;
133         }
134         for (JpaToscaPolicy policy : dbTemplate.getTopologyTemplate().getPolicies().getConceptMap().values()) {
135             if (policy.getMetadata().getOrDefault("metadataSetName", "").equals(name)
136                 && policy.getMetadata().getOrDefault("metadataSetVersion", "").equals(version)) {
137                 throw new PfModelException(Response.Status.NOT_ACCEPTABLE,
138                     "Node template is in use, it is referenced in Tosca Policy " + policy.getName() + " version "
139                         + policy.getVersion());
140             }
141         }
142
143     }
144 }