29a7852f13998e858740281618a6394ec42e531a
[policy/clamp.git] /
1 /*-
2  * ============LICENSE_START=======================================================
3  *  Copyright (C) 2021 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.controlloop.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 lombok.Setter;
31 import org.onap.policy.clamp.controlloop.models.controlloop.concepts.ClElementStatistics;
32 import org.onap.policy.clamp.controlloop.models.controlloop.concepts.ControlLoopElement;
33 import org.onap.policy.clamp.controlloop.models.controlloop.concepts.ControlLoopOrderedState;
34 import org.onap.policy.clamp.controlloop.models.controlloop.concepts.ControlLoopState;
35 import org.onap.policy.clamp.controlloop.models.messages.dmaap.participant.ParticipantMessageType;
36 import org.onap.policy.clamp.controlloop.participant.intermediary.api.ControlLoopElementListener;
37 import org.onap.policy.clamp.controlloop.participant.intermediary.api.ParticipantIntermediaryApi;
38 import org.onap.policy.clamp.controlloop.participant.policy.client.PolicyApiHttpClient;
39 import org.onap.policy.clamp.controlloop.participant.policy.client.PolicyPapHttpClient;
40 import org.onap.policy.models.base.PfModelException;
41 import org.onap.policy.models.base.PfModelRuntimeException;
42 import org.onap.policy.models.tosca.authorative.concepts.ToscaConceptIdentifier;
43 import org.onap.policy.models.tosca.authorative.concepts.ToscaNodeTemplate;
44 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicy;
45 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyType;
46 import org.onap.policy.models.tosca.authorative.concepts.ToscaServiceTemplate;
47 import org.slf4j.Logger;
48 import org.slf4j.LoggerFactory;
49 import org.springframework.stereotype.Component;
50
51 /**
52  * This class handles implementation of controlLoopElement updates.
53  */
54 @Component
55 public class ControlLoopElementHandler implements ControlLoopElementListener {
56
57     private static final Logger LOGGER = LoggerFactory.getLogger(ControlLoopElementHandler.class);
58     private final Map<String, String> policyTypeMap = new LinkedHashMap<>();
59     private final Map<String, String> policyMap = new LinkedHashMap<>();
60
61     private final PolicyApiHttpClient apiHttpClient;
62     private final PolicyPapHttpClient papHttpClient;
63
64     @Setter
65     private ParticipantIntermediaryApi intermediaryApi;
66
67     /**
68      * constructor.
69      *
70      * @param apiHttpClient the Policy Api Http Client
71      * @param papHttpClient the Policy Pap Http Client
72      */
73     public ControlLoopElementHandler(PolicyApiHttpClient apiHttpClient, PolicyPapHttpClient papHttpClient) {
74         this.papHttpClient = papHttpClient;
75         this.apiHttpClient = apiHttpClient;
76     }
77
78     /**
79      * Callback method to handle a control loop element state change.
80      *
81      * @param controlLoopId the ID of the control loop
82      * @param controlLoopElementId the ID of the control loop element
83      * @param currentState the current state of the control loop element
84      * @param orderedState the state to which the control loop element is changing to
85      * @throws PfModelException in case of an exception
86      */
87     @Override
88     public void controlLoopElementStateChange(ToscaConceptIdentifier controlLoopId,
89                 UUID controlLoopElementId, ControlLoopState currentState,
90             ControlLoopOrderedState orderedState) throws PfModelException {
91         switch (orderedState) {
92             case UNINITIALISED:
93                 try {
94                     deletePolicyData(controlLoopId, controlLoopElementId, orderedState);
95                     intermediaryApi.updateControlLoopElementState(controlLoopId,
96                             controlLoopElementId, orderedState, ControlLoopState.UNINITIALISED,
97                             ParticipantMessageType.CONTROL_LOOP_STATE_CHANGE);
98                 } catch (PfModelRuntimeException e) {
99                     LOGGER.debug("Deleting policy data failed", e);
100                 }
101                 break;
102             case PASSIVE:
103                 try {
104                     undeployPolicies(controlLoopElementId, orderedState);
105                 } catch (PfModelRuntimeException e) {
106                     LOGGER.debug("Undeploying policies failed - no policies to undeploy {}", controlLoopElementId);
107                 }
108                 intermediaryApi.updateControlLoopElementState(controlLoopId,
109                         controlLoopElementId, orderedState, ControlLoopState.PASSIVE,
110                         ParticipantMessageType.CONTROL_LOOP_STATE_CHANGE);
111                 break;
112             case RUNNING:
113                 try {
114                     deployPolicies(controlLoopId, controlLoopElementId, orderedState);
115                 } catch (PfModelRuntimeException e) {
116                     LOGGER.debug("Deploying policies failed {}", controlLoopElementId);
117                 }
118                 break;
119             default:
120                 LOGGER.debug("Unknown orderedstate {}", orderedState);
121                 break;
122         }
123     }
124
125     private void deletePolicyData(ToscaConceptIdentifier controlLoopId,
126                                   UUID controlLoopElementId, ControlLoopOrderedState newState) {
127         // Delete all policies of this controlLoop from policy framework
128         for (Entry<String, String> policy : policyMap.entrySet()) {
129             apiHttpClient.deletePolicy(policy.getKey(), policy.getValue());
130         }
131         policyMap.clear();
132         // Delete all policy types of this control loop from policy framework
133         for (Entry<String, String> policyType : policyTypeMap.entrySet()) {
134             apiHttpClient.deletePolicyType(policyType.getKey(), policyType.getValue());
135         }
136         policyTypeMap.clear();
137         intermediaryApi.updateControlLoopElementState(controlLoopId,
138                 controlLoopElementId, newState, ControlLoopState.UNINITIALISED,
139                 ParticipantMessageType.CONTROL_LOOP_STATE_CHANGE);
140     }
141
142     private void deployPolicies(ToscaConceptIdentifier controlLoopId, UUID controlLoopElementId,
143             ControlLoopOrderedState newState) {
144         // Deploy all policies of this controlLoop from Policy Framework
145         if (policyMap.entrySet() != null) {
146             for (Entry<String, String> policy : policyMap.entrySet()) {
147                 papHttpClient.handlePolicyDeployOrUndeploy(policy.getKey(), policy.getValue(), "POST");
148             }
149             LOGGER.debug("Policies deployed to {} successfully", controlLoopElementId);
150         } else {
151             LOGGER.debug("No policies to deploy to {}", controlLoopElementId);
152         }
153         intermediaryApi.updateControlLoopElementState(controlLoopId,
154                 controlLoopElementId, newState, ControlLoopState.RUNNING,
155                 ParticipantMessageType.CONTROL_LOOP_STATE_CHANGE);
156     }
157
158     private void undeployPolicies(UUID controlLoopElementId, ControlLoopOrderedState newState) {
159         // Undeploy all policies of this controlloop from Policy Framework
160         if (policyMap.entrySet() != null) {
161             for (Entry<String, String> policy : policyMap.entrySet()) {
162                 papHttpClient.handlePolicyDeployOrUndeploy(policy.getKey(), policy.getValue(), "DELETE");
163             }
164             LOGGER.debug("Undeployed policies from {} successfully", controlLoopElementId);
165         } else {
166             LOGGER.debug("No policies are deployed to {}", controlLoopElementId);
167         }
168     }
169
170     /**
171      * Callback method to handle an update on a control loop element.
172      *
173      * @param element the information on the control loop element
174      * @param clElementDefinition toscaNodeTemplate
175      * @throws PfModelException in case of an exception
176      */
177     @Override
178     public void controlLoopElementUpdate(ToscaConceptIdentifier controlLoopId, ControlLoopElement element,
179                                          ToscaNodeTemplate clElementDefinition)
180             throws PfModelException {
181         intermediaryApi.updateControlLoopElementState(controlLoopId, element.getId(), element.getOrderedState(),
182                 ControlLoopState.PASSIVE, ParticipantMessageType.CONTROL_LOOP_UPDATE);
183         ToscaServiceTemplate controlLoopDefinition = element.getToscaServiceTemplateFragment();
184         if (controlLoopDefinition.getToscaTopologyTemplate() != null) {
185             if (controlLoopDefinition.getPolicyTypes() != null) {
186                 for (ToscaPolicyType policyType : controlLoopDefinition.getPolicyTypes().values()) {
187                     policyTypeMap.put(policyType.getName(), policyType.getVersion());
188                 }
189                 LOGGER.debug("Found Policy Types in control loop definition: {} , Creating Policy Types",
190                         controlLoopDefinition.getName());
191                 apiHttpClient.createPolicyType(controlLoopDefinition);
192             }
193             if (controlLoopDefinition.getToscaTopologyTemplate().getPolicies() != null) {
194                 for (Map<String, ToscaPolicy> foundPolicyMap : controlLoopDefinition.getToscaTopologyTemplate()
195                         .getPolicies()) {
196                     for (ToscaPolicy policy : foundPolicyMap.values()) {
197                         policyMap.put(policy.getName(), policy.getVersion());
198                     }
199                 }
200                 LOGGER.debug("Found Policies in control loop definition: {} , Creating Policies",
201                         controlLoopDefinition.getName());
202                 apiHttpClient.createPolicy(controlLoopDefinition);
203             }
204         }
205     }
206
207     /**
208      * Handle controlLoopElement statistics.
209      *
210      * @param controlLoopElementId controlloop element id
211      */
212     @Override
213     public void handleStatistics(UUID controlLoopElementId) throws PfModelException {
214         var clElement = intermediaryApi.getControlLoopElement(controlLoopElementId);
215         if (clElement != null) {
216             var clElementStatistics = new ClElementStatistics();
217             clElementStatistics.setControlLoopState(clElement.getState());
218             clElementStatistics.setTimeStamp(Instant.now());
219             intermediaryApi.updateControlLoopElementStatistics(controlLoopElementId, clElementStatistics);
220         }
221     }
222 }