0b03e236fc22ca2406a73886f6a98eeb093807e0
[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.LinkedHashMap;
26 import java.util.Map;
27 import java.util.UUID;
28 import lombok.Setter;
29 import org.apache.http.HttpStatus;
30 import org.onap.policy.clamp.acm.participant.intermediary.api.AutomationCompositionElementListener;
31 import org.onap.policy.clamp.acm.participant.intermediary.api.ParticipantIntermediaryApi;
32 import org.onap.policy.clamp.acm.participant.policy.client.PolicyApiHttpClient;
33 import org.onap.policy.clamp.acm.participant.policy.client.PolicyPapHttpClient;
34 import org.onap.policy.clamp.models.acm.concepts.AcElementDeploy;
35 import org.onap.policy.clamp.models.acm.concepts.DeployState;
36 import org.onap.policy.clamp.models.acm.concepts.LockState;
37 import org.onap.policy.models.base.PfModelException;
38 import org.onap.policy.models.base.PfModelRuntimeException;
39 import org.onap.policy.models.pdp.concepts.DeploymentSubGroup;
40 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicy;
41 import org.slf4j.Logger;
42 import org.slf4j.LoggerFactory;
43 import org.springframework.stereotype.Component;
44
45 /**
46  * This class handles implementation of automationCompositionElement updates.
47  */
48 @Component
49 public class AutomationCompositionElementHandler implements AutomationCompositionElementListener {
50
51     private static final Logger LOGGER = LoggerFactory.getLogger(AutomationCompositionElementHandler.class);
52     private final Map<String, String> policyTypeMap = new LinkedHashMap<>();
53     private final Map<String, String> policyMap = new LinkedHashMap<>();
54
55     private final PolicyApiHttpClient apiHttpClient;
56     private final PolicyPapHttpClient papHttpClient;
57
58     @Setter
59     private ParticipantIntermediaryApi intermediaryApi;
60
61     /**
62      * constructor.
63      *
64      * @param apiHttpClient the Policy Api Http Client
65      * @param papHttpClient the Policy Pap Http Client
66      */
67     public AutomationCompositionElementHandler(PolicyApiHttpClient apiHttpClient, PolicyPapHttpClient papHttpClient) {
68         this.papHttpClient = papHttpClient;
69         this.apiHttpClient = apiHttpClient;
70     }
71
72     /**
73      * Callback method to handle a automation composition element state change.
74      *
75      * @param automationCompositionId the ID of the automation composition
76      * @param automationCompositionElementId the ID of the automation composition element
77      */
78     @Override
79     public void undeploy(UUID automationCompositionId, UUID automationCompositionElementId) {
80         try {
81             undeployPolicies(automationCompositionElementId);
82             deletePolicyData(automationCompositionId, automationCompositionElementId);
83             intermediaryApi.updateAutomationCompositionElementState(automationCompositionId,
84                     automationCompositionElementId, DeployState.UNDEPLOYED, LockState.NONE);
85         } catch (PfModelRuntimeException e) {
86             LOGGER.error("Undeploying/Deleting policy failed {}", automationCompositionElementId, e);
87         }
88     }
89
90     private void deletePolicyData(UUID automationCompositionId, UUID automationCompositionElementId) {
91         // Delete all policies of this automationComposition from policy framework
92         for (var policy : policyMap.entrySet()) {
93             apiHttpClient.deletePolicy(policy.getKey(), policy.getValue());
94         }
95         policyMap.clear();
96         // Delete all policy types of this automation composition from policy framework
97         for (var policyType : policyTypeMap.entrySet()) {
98             apiHttpClient.deletePolicyType(policyType.getKey(), policyType.getValue());
99         }
100         policyTypeMap.clear();
101     }
102
103     private void deployPolicies(UUID automationCompositionId, UUID automationCompositionElementId) {
104         var deployFailure = false;
105         // Deploy all policies of this automationComposition from Policy Framework
106         if (!policyMap.entrySet().isEmpty()) {
107             for (var policy : policyMap.entrySet()) {
108                 var deployPolicyResp = papHttpClient.handlePolicyDeployOrUndeploy(policy.getKey(), policy.getValue(),
109                         DeploymentSubGroup.Action.POST).getStatus();
110                 if (deployPolicyResp != HttpStatus.SC_ACCEPTED) {
111                     deployFailure = true;
112                 }
113             }
114             LOGGER.info("Policies deployed to {} successfully", automationCompositionElementId);
115         } else {
116             LOGGER.debug("No policies to deploy to {}", automationCompositionElementId);
117         }
118         if (!deployFailure) {
119             // Update the AC element state
120             intermediaryApi.updateAutomationCompositionElementState(automationCompositionId,
121                     automationCompositionElementId, DeployState.DEPLOYED, LockState.LOCKED);
122         }
123     }
124
125     private void undeployPolicies(UUID automationCompositionElementId) {
126         // Undeploy all policies of this automation composition from Policy Framework
127         if (!policyMap.entrySet().isEmpty()) {
128             for (var policy : policyMap.entrySet()) {
129                 papHttpClient.handlePolicyDeployOrUndeploy(policy.getKey(), policy.getValue(),
130                         DeploymentSubGroup.Action.DELETE);
131             }
132             LOGGER.debug("Undeployed policies from {} successfully", automationCompositionElementId);
133         } else {
134             LOGGER.debug("No policies are deployed to {}", automationCompositionElementId);
135         }
136     }
137
138     /**
139      * Callback method to handle an update on automation composition element.
140      *
141      * @param automationCompositionId the automationComposition Id
142      * @param element the information on the automation composition element
143      * @param properties properties Map
144      * @throws PfModelException in case of an exception
145      */
146     @Override
147     public void deploy(UUID automationCompositionId, AcElementDeploy element, Map<String, Object> properties)
148             throws PfModelException {
149         var createPolicyTypeResp = HttpStatus.SC_OK;
150         var createPolicyResp = HttpStatus.SC_OK;
151
152         var automationCompositionDefinition = element.getToscaServiceTemplateFragment();
153         if (automationCompositionDefinition.getToscaTopologyTemplate() != null) {
154             if (automationCompositionDefinition.getPolicyTypes() != null) {
155                 for (var policyType : automationCompositionDefinition.getPolicyTypes().values()) {
156                     policyTypeMap.put(policyType.getName(), policyType.getVersion());
157                 }
158                 LOGGER.info("Found Policy Types in automation composition definition: {} , Creating Policy Types",
159                         automationCompositionDefinition.getName());
160                 createPolicyTypeResp = apiHttpClient.createPolicyType(automationCompositionDefinition).getStatus();
161             }
162             if (automationCompositionDefinition.getToscaTopologyTemplate().getPolicies() != null) {
163                 for (var gotPolicyMap : automationCompositionDefinition.getToscaTopologyTemplate().getPolicies()) {
164                     for (ToscaPolicy policy : gotPolicyMap.values()) {
165                         policyMap.put(policy.getName(), policy.getVersion());
166                     }
167                 }
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("PolicyTypes/Policies for the automation composition element : {} are created "
174                         + "successfully", element.getId());
175                 deployPolicies(automationCompositionId, element.getId());
176             } else {
177                 LOGGER.error("Creation of PolicyTypes/Policies failed. Policies will not be deployed.");
178             }
179         }
180     }
181 }