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