e020d209eecf794c12ca60c877c5669c12046716
[policy/clamp.git] /
1 /*-
2  * ============LICENSE_START=======================================================
3  *  Copyright (C) 2021,2022 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.time.Instant;
26 import java.util.LinkedHashMap;
27 import java.util.Map;
28 import java.util.Map.Entry;
29 import java.util.UUID;
30 import javax.ws.rs.core.Response;
31 import lombok.Setter;
32 import org.apache.http.HttpStatus;
33 import org.onap.policy.clamp.acm.participant.intermediary.api.AutomationCompositionElementListener;
34 import org.onap.policy.clamp.acm.participant.intermediary.api.ParticipantIntermediaryApi;
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.AcElementStatistics;
38 import org.onap.policy.clamp.models.acm.concepts.AutomationCompositionElement;
39 import org.onap.policy.clamp.models.acm.concepts.AutomationCompositionOrderedState;
40 import org.onap.policy.clamp.models.acm.concepts.AutomationCompositionState;
41 import org.onap.policy.clamp.models.acm.messages.dmaap.participant.ParticipantMessageType;
42 import org.onap.policy.models.base.PfModelException;
43 import org.onap.policy.models.base.PfModelRuntimeException;
44 import org.onap.policy.models.pdp.concepts.DeploymentSubGroup;
45 import org.onap.policy.models.tosca.authorative.concepts.ToscaConceptIdentifier;
46 import org.onap.policy.models.tosca.authorative.concepts.ToscaNodeTemplate;
47 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicy;
48 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyType;
49 import org.onap.policy.models.tosca.authorative.concepts.ToscaServiceTemplate;
50 import org.slf4j.Logger;
51 import org.slf4j.LoggerFactory;
52 import org.springframework.stereotype.Component;
53
54 /**
55  * This class handles implementation of automationCompositionElement updates.
56  */
57 @Component
58 public class AutomationCompositionElementHandler implements AutomationCompositionElementListener {
59
60     private static final Logger LOGGER = LoggerFactory.getLogger(AutomationCompositionElementHandler.class);
61     private final Map<String, String> policyTypeMap = new LinkedHashMap<>();
62     private final Map<String, String> policyMap = new LinkedHashMap<>();
63
64     private final PolicyApiHttpClient apiHttpClient;
65     private final PolicyPapHttpClient papHttpClient;
66
67     @Setter
68     private ParticipantIntermediaryApi intermediaryApi;
69
70     /**
71      * constructor.
72      *
73      * @param apiHttpClient the Policy Api Http Client
74      * @param papHttpClient the Policy Pap Http Client
75      */
76     public AutomationCompositionElementHandler(PolicyApiHttpClient apiHttpClient, PolicyPapHttpClient papHttpClient) {
77         this.papHttpClient = papHttpClient;
78         this.apiHttpClient = apiHttpClient;
79     }
80
81     /**
82      * Callback method to handle a automation composition element state change.
83      *
84      * @param automationCompositionId        the ID of the automation composition
85      * @param automationCompositionElementId the ID of the automation composition element
86      * @param currentState                   the current state of the automation composition element
87      * @param orderedState                   the state to which the automation composition element is changing to
88      */
89     @Override
90     public void automationCompositionElementStateChange(ToscaConceptIdentifier automationCompositionId,
91                                                         UUID automationCompositionElementId,
92                                                         AutomationCompositionState currentState,
93                                                         AutomationCompositionOrderedState orderedState) {
94         switch (orderedState) {
95             case UNINITIALISED:
96                 try {
97                     undeployPolicies(automationCompositionElementId);
98                     deletePolicyData(automationCompositionId, automationCompositionElementId, orderedState);
99                     intermediaryApi.updateAutomationCompositionElementState(automationCompositionId,
100                         automationCompositionElementId, orderedState, AutomationCompositionState.UNINITIALISED,
101                         ParticipantMessageType.AUTOMATION_COMPOSITION_STATE_CHANGE);
102                 } catch (PfModelRuntimeException e) {
103                     LOGGER.error("Undeploying/Deleting policy failed {}", automationCompositionElementId, e);
104                 }
105                 break;
106             case PASSIVE:
107                 try {
108                     undeployPolicies(automationCompositionElementId);
109                 } catch (PfModelRuntimeException e) {
110                     LOGGER.error("Undeploying policies failed - no policies to undeploy {}",
111                         automationCompositionElementId);
112                 }
113                 intermediaryApi.updateAutomationCompositionElementState(automationCompositionId,
114                     automationCompositionElementId, orderedState, AutomationCompositionState.PASSIVE,
115                     ParticipantMessageType.AUTOMATION_COMPOSITION_STATE_CHANGE);
116                 break;
117             case RUNNING:
118                 LOGGER.info("Running state is not supported");
119                 break;
120             default:
121                 LOGGER.debug("Unknown orderedstate {}", orderedState);
122                 break;
123         }
124     }
125
126     private void deletePolicyData(ToscaConceptIdentifier automationCompositionId,
127                                   UUID automationCompositionElementId, AutomationCompositionOrderedState newState) {
128         // Delete all policies of this automationComposition from policy framework
129         for (Entry<String, String> policy : policyMap.entrySet()) {
130             apiHttpClient.deletePolicy(policy.getKey(), policy.getValue());
131         }
132         policyMap.clear();
133         // Delete all policy types of this automation composition from policy framework
134         for (Entry<String, String> policyType : policyTypeMap.entrySet()) {
135             apiHttpClient.deletePolicyType(policyType.getKey(), policyType.getValue());
136         }
137         policyTypeMap.clear();
138     }
139
140     private void deployPolicies(ToscaConceptIdentifier automationCompositionId, UUID automationCompositionElementId,
141                                 AutomationCompositionOrderedState newState) {
142         var deployFailure = false;
143         // Deploy all policies of this automationComposition from Policy Framework
144         if (!policyMap.entrySet().isEmpty()) {
145             for (Entry<String, String> policy : policyMap.entrySet()) {
146                 var deployPolicyResp = papHttpClient.handlePolicyDeployOrUndeploy(policy.getKey(), policy.getValue(),
147                         DeploymentSubGroup.Action.POST).getStatus();
148                 if (deployPolicyResp != HttpStatus.SC_ACCEPTED) {
149                     deployFailure = true;
150                 }
151             }
152             LOGGER.info("Policies deployed to {} successfully", automationCompositionElementId);
153         } else {
154             LOGGER.debug("No policies to deploy to {}", automationCompositionElementId);
155         }
156         if (! deployFailure) {
157             // Update the AC element state
158             intermediaryApi.updateAutomationCompositionElementState(automationCompositionId,
159                     automationCompositionElementId, newState, AutomationCompositionState.PASSIVE,
160                     ParticipantMessageType.AUTOMATION_COMPOSITION_STATE_CHANGE);
161         }
162     }
163
164     private void undeployPolicies(UUID automationCompositionElementId) {
165         // Undeploy all policies of this automation composition from Policy Framework
166         if (!policyMap.entrySet().isEmpty()) {
167             for (Entry<String, String> policy : policyMap.entrySet()) {
168                 papHttpClient.handlePolicyDeployOrUndeploy(policy.getKey(), policy.getValue(),
169                     DeploymentSubGroup.Action.DELETE);
170             }
171             LOGGER.debug("Undeployed policies from {} successfully", automationCompositionElementId);
172         } else {
173             LOGGER.debug("No policies are deployed to {}", automationCompositionElementId);
174         }
175     }
176
177     /**
178      * Callback method to handle an update on a automation composition element.
179      *
180      * @param element             the information on the automation composition element
181      * @param acElementDefinition toscaNodeTemplate
182      * @throws PfModelException in case of an exception
183      */
184     @Override
185     public void automationCompositionElementUpdate(ToscaConceptIdentifier automationCompositionId,
186                                                    AutomationCompositionElement element,
187                                                    ToscaNodeTemplate acElementDefinition)
188         throws PfModelException {
189         var createPolicyTypeResp = HttpStatus.SC_OK;
190         var createPolicyResp = HttpStatus.SC_OK;
191
192         ToscaServiceTemplate automationCompositionDefinition = element.getToscaServiceTemplateFragment();
193         if (automationCompositionDefinition.getToscaTopologyTemplate() != null) {
194             if (automationCompositionDefinition.getPolicyTypes() != null) {
195                 for (ToscaPolicyType policyType : automationCompositionDefinition.getPolicyTypes().values()) {
196                     policyTypeMap.put(policyType.getName(), policyType.getVersion());
197                 }
198                 LOGGER.info("Found Policy Types in automation composition definition: {} , Creating Policy Types",
199                     automationCompositionDefinition.getName());
200                 createPolicyTypeResp = apiHttpClient.createPolicyType(automationCompositionDefinition).getStatus();
201             }
202             if (automationCompositionDefinition.getToscaTopologyTemplate().getPolicies() != null) {
203                 for (Map<String, ToscaPolicy> gotPolicyMap : automationCompositionDefinition.getToscaTopologyTemplate()
204                     .getPolicies()) {
205                     for (ToscaPolicy policy : gotPolicyMap.values()) {
206                         policyMap.put(policy.getName(), policy.getVersion());
207                     }
208                 }
209                 LOGGER.info("Found Policies in automation composition definition: {} , Creating Policies",
210                     automationCompositionDefinition.getName());
211                 createPolicyResp = apiHttpClient.createPolicy(automationCompositionDefinition).getStatus();
212             }
213             if (createPolicyTypeResp == HttpStatus.SC_OK && createPolicyResp == HttpStatus.SC_OK) {
214                 LOGGER.info("PolicyTypes/Policies for the automation composition element : {} are created "
215                         + "successfully", element.getId());
216                 deployPolicies(automationCompositionId, element.getId(), element.getOrderedState());
217             } else {
218                 LOGGER.error("Creation of PolicyTypes/Policies failed. Policies will not be deployed.");
219             }
220         }
221     }
222
223     /**
224      * Handle automationCompositionElement statistics.
225      *
226      * @param automationCompositionElementId automation composition element id
227      */
228     @Override
229     public void handleStatistics(UUID automationCompositionElementId) {
230         var acElement = intermediaryApi.getAutomationCompositionElement(automationCompositionElementId);
231         if (acElement != null) {
232             var acElementStatistics = new AcElementStatistics();
233             acElementStatistics.setState(acElement.getState());
234             acElementStatistics.setTimeStamp(Instant.now());
235             intermediaryApi.updateAutomationCompositionElementStatistics(automationCompositionElementId,
236                 acElementStatistics);
237         }
238     }
239 }