627f791312bc12ef8740f2304d272dce29b99039
[policy/clamp.git] /
1 /*-
2  * ============LICENSE_START=======================================================
3  *  Copyright (C) 2021-2023 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.acm.participant.policy.main.handler;
24
25 import java.util.ArrayList;
26 import java.util.LinkedHashMap;
27 import java.util.List;
28 import java.util.Map;
29 import java.util.UUID;
30 import javax.ws.rs.core.Response.Status;
31 import lombok.RequiredArgsConstructor;
32 import lombok.Setter;
33 import org.apache.http.HttpStatus;
34 import org.onap.policy.clamp.acm.participant.intermediary.api.AutomationCompositionElementListener;
35 import org.onap.policy.clamp.acm.participant.intermediary.api.ParticipantIntermediaryApi;
36 import org.onap.policy.clamp.acm.participant.policy.client.PolicyApiHttpClient;
37 import org.onap.policy.clamp.acm.participant.policy.client.PolicyPapHttpClient;
38 import org.onap.policy.clamp.models.acm.concepts.AcElementDeploy;
39 import org.onap.policy.clamp.models.acm.concepts.DeployState;
40 import org.onap.policy.models.base.PfModelException;
41 import org.onap.policy.models.pdp.concepts.DeploymentSubGroup;
42 import org.onap.policy.models.tosca.authorative.concepts.ToscaConceptIdentifier;
43 import org.onap.policy.models.tosca.authorative.concepts.ToscaServiceTemplate;
44 import org.slf4j.Logger;
45 import org.slf4j.LoggerFactory;
46 import org.springframework.stereotype.Component;
47
48 /**
49  * This class handles implementation of automationCompositionElement updates.
50  */
51 @Component
52 @RequiredArgsConstructor
53 public class AutomationCompositionElementHandler implements AutomationCompositionElementListener {
54
55     private static final Logger LOGGER = LoggerFactory.getLogger(AutomationCompositionElementHandler.class);
56
57     private final Map<UUID, ToscaServiceTemplate> serviceTemplateMap = new LinkedHashMap<>();
58
59     private final PolicyApiHttpClient apiHttpClient;
60     private final PolicyPapHttpClient papHttpClient;
61
62     @Setter
63     private ParticipantIntermediaryApi intermediaryApi;
64
65     /**
66      * Callback method to handle a automation composition element state change.
67      *
68      * @param automationCompositionId the ID of the automation composition
69      * @param automationCompositionElementId the ID of the automation composition element
70      */
71     @Override
72     public void undeploy(UUID automationCompositionId, UUID automationCompositionElementId) throws PfModelException {
73         var automationCompositionDefinition = serviceTemplateMap.get(automationCompositionElementId);
74         if (automationCompositionDefinition == null) {
75             LOGGER.debug("No policies to undeploy to {}", automationCompositionElementId);
76             intermediaryApi.updateAutomationCompositionElementState(automationCompositionId,
77                     automationCompositionElementId, DeployState.UNDEPLOYED, null, "Undeployed");
78             return;
79         }
80         var policyList = getPolicyList(automationCompositionDefinition);
81         undeployPolicies(policyList, automationCompositionElementId);
82         var policyTypeList = getPolicyTypeList(automationCompositionDefinition);
83         deletePolicyData(policyTypeList, policyList);
84         serviceTemplateMap.remove(automationCompositionElementId);
85         intermediaryApi.updateAutomationCompositionElementState(automationCompositionId,
86                 automationCompositionElementId, DeployState.UNDEPLOYED, null, "Undeployed");
87     }
88
89     private void deletePolicyData(List<ToscaConceptIdentifier> policyTypeList,
90             List<ToscaConceptIdentifier> policyList) {
91         // Delete all policies of this automationComposition from policy framework
92         for (var policy : policyList) {
93             apiHttpClient.deletePolicy(policy.getName(), policy.getVersion());
94         }
95         // Delete all policy types of this automation composition from policy framework
96         for (var policyType : policyTypeList) {
97             apiHttpClient.deletePolicyType(policyType.getName(), policyType.getVersion());
98         }
99     }
100
101     private void deployPolicies(List<ToscaConceptIdentifier> policyList, UUID automationCompositionId,
102             UUID automationCompositionElementId) throws PfModelException {
103         var deployFailure = false;
104         // Deploy all policies of this automationComposition from Policy Framework
105         if (!policyList.isEmpty()) {
106             for (var policy : policyList) {
107                 var deployPolicyResp = papHttpClient.handlePolicyDeployOrUndeploy(policy.getName(), policy.getVersion(),
108                         DeploymentSubGroup.Action.POST).getStatus();
109                 if (deployPolicyResp != HttpStatus.SC_ACCEPTED) {
110                     deployFailure = true;
111                 }
112             }
113             LOGGER.info("Policies deployed to {} successfully", automationCompositionElementId);
114         } else {
115             LOGGER.debug("No policies to deploy to {}", automationCompositionElementId);
116         }
117         if (!deployFailure) {
118             // Update the AC element state
119             intermediaryApi.sendAcElementInfo(automationCompositionId, automationCompositionElementId, "IDLE",
120                     "ENABLED", Map.of());
121             intermediaryApi.updateAutomationCompositionElementState(automationCompositionId,
122                     automationCompositionElementId, DeployState.DEPLOYED, null, "Deployed");
123         } else {
124             throw new PfModelException(Status.BAD_REQUEST, "Deploy of Policy failed.");
125         }
126     }
127
128     private void undeployPolicies(List<ToscaConceptIdentifier> policyList, UUID automationCompositionElementId) {
129         // Undeploy all policies of this automation composition from Policy Framework
130         if (!policyList.isEmpty()) {
131             for (var policy : policyList) {
132                 papHttpClient.handlePolicyDeployOrUndeploy(policy.getName(), policy.getVersion(),
133                         DeploymentSubGroup.Action.DELETE);
134             }
135             LOGGER.debug("Undeployed policies from {} successfully", automationCompositionElementId);
136         } else {
137             LOGGER.debug("No policies are deployed to {}", automationCompositionElementId);
138         }
139     }
140
141     /**
142      * Callback method to handle an update on automation composition element.
143      *
144      * @param automationCompositionId the automationComposition Id
145      * @param element the information on the automation composition element
146      * @param properties properties Map
147      * @throws PfModelException in case of an exception
148      */
149     @Override
150     public void deploy(UUID automationCompositionId, AcElementDeploy element, Map<String, Object> properties)
151             throws PfModelException {
152         var createPolicyTypeResp = HttpStatus.SC_OK;
153         var createPolicyResp = HttpStatus.SC_OK;
154
155         var automationCompositionDefinition = element.getToscaServiceTemplateFragment();
156         if (automationCompositionDefinition.getToscaTopologyTemplate() == null) {
157             throw new PfModelException(Status.BAD_REQUEST, "ToscaTopologyTemplate not defined");
158         }
159         serviceTemplateMap.put(element.getId(), automationCompositionDefinition);
160         if (automationCompositionDefinition.getPolicyTypes() != null) {
161             LOGGER.info("Found Policy Types in automation composition definition: {} , Creating Policy Types",
162                     automationCompositionDefinition.getName());
163             createPolicyTypeResp = apiHttpClient.createPolicyType(automationCompositionDefinition).getStatus();
164         }
165         if (automationCompositionDefinition.getToscaTopologyTemplate().getPolicies() != null) {
166             LOGGER.info("Found Policies in automation composition definition: {} , Creating Policies",
167                     automationCompositionDefinition.getName());
168             createPolicyResp = apiHttpClient.createPolicy(automationCompositionDefinition).getStatus();
169         }
170         if (createPolicyTypeResp == HttpStatus.SC_OK && createPolicyResp == HttpStatus.SC_OK) {
171             LOGGER.info(
172                     "PolicyTypes/Policies for the automation composition element : {} are created " + "successfully",
173                     element.getId());
174             var policyList = getPolicyList(automationCompositionDefinition);
175             deployPolicies(policyList, automationCompositionId, element.getId());
176         } else {
177             throw new PfModelException(Status.BAD_REQUEST,
178                     "Creation of PolicyTypes/Policies failed. Policies will not be deployed.");
179         }
180     }
181
182     private List<ToscaConceptIdentifier> getPolicyTypeList(ToscaServiceTemplate serviceTemplate) {
183         List<ToscaConceptIdentifier> policyTypeList = new ArrayList<>();
184         if (serviceTemplate.getPolicyTypes() != null) {
185             for (var policyType : serviceTemplate.getPolicyTypes().values()) {
186                 policyTypeList.add(policyType.getKey().asIdentifier());
187             }
188         }
189
190         return policyTypeList;
191     }
192
193     private List<ToscaConceptIdentifier> getPolicyList(ToscaServiceTemplate serviceTemplate) {
194         List<ToscaConceptIdentifier> policyList = new ArrayList<>();
195         if (serviceTemplate.getToscaTopologyTemplate().getPolicies() != null) {
196             for (var gotPolicyMap : serviceTemplate.getToscaTopologyTemplate().getPolicies()) {
197                 for (var policy : gotPolicyMap.values()) {
198                     policyList.add(policy.getKey().asIdentifier());
199                 }
200             }
201         }
202
203         return policyList;
204     }
205 }