5cf79acf8811bdb66b20952a528341fa9867211a
[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.acm.participant.policy.main.handler;
24
25 import jakarta.ws.rs.core.Response.Status;
26 import java.util.ArrayList;
27 import java.util.List;
28 import java.util.Map;
29 import java.util.UUID;
30 import org.apache.http.HttpStatus;
31 import org.onap.policy.clamp.acm.participant.intermediary.api.CompositionElementDto;
32 import org.onap.policy.clamp.acm.participant.intermediary.api.InstanceElementDto;
33 import org.onap.policy.clamp.acm.participant.intermediary.api.ParticipantIntermediaryApi;
34 import org.onap.policy.clamp.acm.participant.intermediary.api.impl.AcElementListenerV2;
35 import org.onap.policy.clamp.acm.participant.policy.client.PolicyApiHttpClient;
36 import org.onap.policy.clamp.acm.participant.policy.client.PolicyPapHttpClient;
37 import org.onap.policy.clamp.models.acm.concepts.DeployState;
38 import org.onap.policy.clamp.models.acm.concepts.StateChangeResult;
39 import org.onap.policy.common.utils.coder.Coder;
40 import org.onap.policy.common.utils.coder.CoderException;
41 import org.onap.policy.common.utils.coder.StandardCoder;
42 import org.onap.policy.models.base.PfModelException;
43 import org.onap.policy.models.pdp.concepts.DeploymentSubGroup;
44 import org.onap.policy.models.tosca.authorative.concepts.ToscaConceptIdentifier;
45 import org.onap.policy.models.tosca.authorative.concepts.ToscaServiceTemplate;
46 import org.slf4j.Logger;
47 import org.slf4j.LoggerFactory;
48 import org.springframework.stereotype.Component;
49
50 /**
51  * This class handles implementation of automationCompositionElement updates.
52  */
53 @Component
54 public class AutomationCompositionElementHandler extends AcElementListenerV2 {
55
56     private static final Logger LOGGER = LoggerFactory.getLogger(AutomationCompositionElementHandler.class);
57     private static final Coder CODER = new StandardCoder();
58
59     private final PolicyApiHttpClient apiHttpClient;
60     private final PolicyPapHttpClient papHttpClient;
61
62     /**
63      * Constructor.
64      *
65      * @param apiHttpClient the PolicyApi Http Client
66      * @param papHttpClient the Policy Pap Http Client
67      * @param intermediaryApi the Participant Intermediary Api
68      */
69     public AutomationCompositionElementHandler(PolicyApiHttpClient apiHttpClient, PolicyPapHttpClient papHttpClient,
70         ParticipantIntermediaryApi intermediaryApi) {
71         super(intermediaryApi);
72         this.apiHttpClient = apiHttpClient;
73         this.papHttpClient = papHttpClient;
74     }
75
76     /**
77      * Callback method to handle a automation composition element state change.
78      *
79      * @param compositionElement the information of the Automation Composition Definition Element
80      * @param instanceElement the information of the Automation Composition Instance Element
81      * @throws PfModelException in case of a model exception
82      */
83     @Override
84     public void undeploy(CompositionElementDto compositionElement, InstanceElementDto instanceElement)
85             throws PfModelException {
86         var automationCompositionDefinition = getToscaServiceTemplate(instanceElement.inProperties());
87         if (automationCompositionDefinition.getToscaTopologyTemplate() == null) {
88             LOGGER.debug("No policies to undeploy to {}", instanceElement.elementId());
89             intermediaryApi.updateAutomationCompositionElementState(instanceElement.instanceId(),
90                     instanceElement.elementId(), DeployState.UNDEPLOYED, null, StateChangeResult.NO_ERROR,
91                     "Undeployed");
92             return;
93         }
94         var policyList = getPolicyList(automationCompositionDefinition);
95         undeployPolicies(policyList, instanceElement.elementId());
96         var policyTypeList = getPolicyTypeList(automationCompositionDefinition);
97         deletePolicyData(policyTypeList, policyList);
98         intermediaryApi.updateAutomationCompositionElementState(instanceElement.instanceId(),
99                 instanceElement.elementId(), DeployState.UNDEPLOYED, null, StateChangeResult.NO_ERROR,
100                 "Undeployed");
101     }
102
103     private void deletePolicyData(List<ToscaConceptIdentifier> policyTypeList,
104             List<ToscaConceptIdentifier> policyList) {
105         // Delete all policies of this automationComposition from policy framework
106         for (var policy : policyList) {
107             apiHttpClient.deletePolicy(policy.getName(), policy.getVersion());
108         }
109         // Delete all policy types of this automation composition from policy framework
110         for (var policyType : policyTypeList) {
111             apiHttpClient.deletePolicyType(policyType.getName(), policyType.getVersion());
112         }
113     }
114
115     private void deployPolicies(List<ToscaConceptIdentifier> policyList, UUID automationCompositionId,
116             UUID automationCompositionElementId) throws PfModelException {
117         var deployFailure = false;
118         // Deploy all policies of this automationComposition from Policy Framework
119         if (!policyList.isEmpty()) {
120             for (var policy : policyList) {
121                 var deployPolicyResp = papHttpClient.handlePolicyDeployOrUndeploy(policy.getName(), policy.getVersion(),
122                         DeploymentSubGroup.Action.POST).getStatus();
123                 if (deployPolicyResp != HttpStatus.SC_ACCEPTED) {
124                     deployFailure = true;
125                 }
126             }
127             LOGGER.info("Policies deployed to {} successfully", automationCompositionElementId);
128         } else {
129             LOGGER.debug("No policies to deploy to {}", automationCompositionElementId);
130         }
131         if (!deployFailure) {
132             // Update the AC element state
133             intermediaryApi.sendAcElementInfo(automationCompositionId, automationCompositionElementId, "IDLE",
134                     "ENABLED", Map.of());
135             intermediaryApi.updateAutomationCompositionElementState(automationCompositionId,
136                     automationCompositionElementId, DeployState.DEPLOYED, null, StateChangeResult.NO_ERROR, "Deployed");
137         } else {
138             throw new PfModelException(Status.BAD_REQUEST, "Deploy of Policy failed.");
139         }
140     }
141
142     private void undeployPolicies(List<ToscaConceptIdentifier> policyList, UUID automationCompositionElementId) {
143         // Undeploy all policies of this automation composition from Policy Framework
144         if (!policyList.isEmpty()) {
145             for (var policy : policyList) {
146                 papHttpClient.handlePolicyDeployOrUndeploy(policy.getName(), policy.getVersion(),
147                         DeploymentSubGroup.Action.DELETE);
148             }
149             LOGGER.debug("Undeployed policies from {} successfully", automationCompositionElementId);
150         } else {
151             LOGGER.debug("No policies are deployed to {}", automationCompositionElementId);
152         }
153     }
154
155     /**
156      * Callback method to handle an update on automation composition element.
157      *
158      * @param compositionElement the information of the Automation Composition Definition Element
159      * @param instanceElement the information of the Automation Composition Instance Element
160      * @throws PfModelException from Policy framework
161      */
162     @Override
163     public void deploy(CompositionElementDto compositionElement, InstanceElementDto instanceElement)
164             throws PfModelException {
165         var createPolicyTypeResp = HttpStatus.SC_OK;
166         var createPolicyResp = HttpStatus.SC_OK;
167
168         var automationCompositionDefinition = getToscaServiceTemplate(instanceElement.inProperties());
169         if (automationCompositionDefinition.getToscaTopologyTemplate() == null) {
170             intermediaryApi.updateAutomationCompositionElementState(instanceElement.instanceId(),
171                     instanceElement.elementId(), DeployState.UNDEPLOYED, null, StateChangeResult.FAILED,
172                     "ToscaTopologyTemplate not defined");
173             return;
174         }
175         if (automationCompositionDefinition.getPolicyTypes() != null) {
176             LOGGER.info("Found Policy Types in automation composition definition: {} , Creating Policy Types",
177                     automationCompositionDefinition.getName());
178             try (var response = apiHttpClient.createPolicyType(automationCompositionDefinition)) {
179                 createPolicyTypeResp = response.getStatus();
180             }
181         }
182         if (automationCompositionDefinition.getToscaTopologyTemplate().getPolicies() != null) {
183             LOGGER.info("Found Policies in automation composition definition: {} , Creating Policies",
184                     automationCompositionDefinition.getName());
185             try (var response = apiHttpClient.createPolicy(automationCompositionDefinition)) {
186                 createPolicyResp = response.getStatus();
187             }
188         }
189         if (isSuccess(createPolicyTypeResp) && isSuccess(createPolicyResp)) {
190             LOGGER.info(
191                     "PolicyTypes/Policies for the automation composition element : {} are created " + "successfully",
192                     instanceElement.elementId());
193             var policyList = getPolicyList(automationCompositionDefinition);
194             deployPolicies(policyList, instanceElement.instanceId(), instanceElement.elementId());
195         } else {
196             intermediaryApi.updateAutomationCompositionElementState(instanceElement.instanceId(),
197                     instanceElement.elementId(), DeployState.UNDEPLOYED, null, StateChangeResult.FAILED,
198                     "Creation of PolicyTypes/Policies failed. Policies will not be deployed.");
199         }
200     }
201
202     private boolean isSuccess(int status) {
203         return status == HttpStatus.SC_OK || status == HttpStatus.SC_CREATED;
204     }
205
206     private List<ToscaConceptIdentifier> getPolicyTypeList(ToscaServiceTemplate serviceTemplate) {
207         List<ToscaConceptIdentifier> policyTypeList = new ArrayList<>();
208         if (serviceTemplate.getPolicyTypes() != null) {
209             for (var policyType : serviceTemplate.getPolicyTypes().values()) {
210                 policyTypeList.add(policyType.getKey().asIdentifier());
211             }
212         }
213
214         return policyTypeList;
215     }
216
217     private List<ToscaConceptIdentifier> getPolicyList(ToscaServiceTemplate serviceTemplate) {
218         List<ToscaConceptIdentifier> policyList = new ArrayList<>();
219         if (serviceTemplate.getToscaTopologyTemplate().getPolicies() != null) {
220             for (var gotPolicyMap : serviceTemplate.getToscaTopologyTemplate().getPolicies()) {
221                 for (var policy : gotPolicyMap.values()) {
222                     policyList.add(policy.getKey().asIdentifier());
223                 }
224             }
225         }
226
227         return policyList;
228     }
229
230     private ToscaServiceTemplate getToscaServiceTemplate(Map<String, Object> properties) throws PfModelException {
231         try {
232             return  CODER.convert(properties, ToscaServiceTemplate.class);
233         } catch (CoderException e) {
234             throw new PfModelException(Status.BAD_REQUEST, e.getMessage());
235         }
236     }
237 }