5eb997e522d4fd981d9c6509efbda26b9e24e22a
[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             intermediaryApi.updateAutomationCompositionElementState(automationCompositionId, element.getId(),
158                     DeployState.UNDEPLOYED, null, "ToscaTopologyTemplate not defined");
159             return;
160         }
161         serviceTemplateMap.put(element.getId(), automationCompositionDefinition);
162         if (automationCompositionDefinition.getPolicyTypes() != null) {
163             LOGGER.info("Found Policy Types in automation composition definition: {} , Creating Policy Types",
164                     automationCompositionDefinition.getName());
165             createPolicyTypeResp = apiHttpClient.createPolicyType(automationCompositionDefinition).getStatus();
166         }
167         if (automationCompositionDefinition.getToscaTopologyTemplate().getPolicies() != null) {
168             LOGGER.info("Found Policies in automation composition definition: {} , Creating Policies",
169                     automationCompositionDefinition.getName());
170             createPolicyResp = apiHttpClient.createPolicy(automationCompositionDefinition).getStatus();
171         }
172         if (createPolicyTypeResp == HttpStatus.SC_OK && createPolicyResp == HttpStatus.SC_OK) {
173             LOGGER.info(
174                     "PolicyTypes/Policies for the automation composition element : {} are created " + "successfully",
175                     element.getId());
176             var policyList = getPolicyList(automationCompositionDefinition);
177             deployPolicies(policyList, automationCompositionId, element.getId());
178         } else {
179             intermediaryApi.updateAutomationCompositionElementState(automationCompositionId, element.getId(),
180                     DeployState.UNDEPLOYED, null,
181                     "Creation of PolicyTypes/Policies failed. Policies will not be deployed.");
182         }
183     }
184
185     private List<ToscaConceptIdentifier> getPolicyTypeList(ToscaServiceTemplate serviceTemplate) {
186         List<ToscaConceptIdentifier> policyTypeList = new ArrayList<>();
187         if (serviceTemplate.getPolicyTypes() != null) {
188             for (var policyType : serviceTemplate.getPolicyTypes().values()) {
189                 policyTypeList.add(policyType.getKey().asIdentifier());
190             }
191         }
192
193         return policyTypeList;
194     }
195
196     private List<ToscaConceptIdentifier> getPolicyList(ToscaServiceTemplate serviceTemplate) {
197         List<ToscaConceptIdentifier> policyList = new ArrayList<>();
198         if (serviceTemplate.getToscaTopologyTemplate().getPolicies() != null) {
199             for (var gotPolicyMap : serviceTemplate.getToscaTopologyTemplate().getPolicies()) {
200                 for (var policy : gotPolicyMap.values()) {
201                     policyList.add(policy.getKey().asIdentifier());
202                 }
203             }
204         }
205
206         return policyList;
207     }
208 }