20a23ca3232212edb0e70b7bc46a0fe33ab03b02
[policy/clamp.git] /
1 /*-
2  * ============LICENSE_START=======================================================
3  *  Copyright (C) 2021 Nordix Foundation.
4  * ================================================================================
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  *      http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  *
17  * SPDX-License-Identifier: Apache-2.0
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.onap.policy.clamp.controlloop.participant.kubernetes.handler;
22
23
24 import java.io.IOException;
25 import java.lang.invoke.MethodHandles;
26 import java.util.HashMap;
27 import java.util.Map;
28 import java.util.UUID;
29 import java.util.concurrent.ConcurrentHashMap;
30 import lombok.AccessLevel;
31 import lombok.Getter;
32 import lombok.Setter;
33 import org.onap.policy.clamp.controlloop.models.controlloop.concepts.ControlLoopElement;
34 import org.onap.policy.clamp.controlloop.models.controlloop.concepts.ControlLoopOrderedState;
35 import org.onap.policy.clamp.controlloop.models.controlloop.concepts.ControlLoopState;
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.kubernetes.exception.ServiceException;
39 import org.onap.policy.clamp.controlloop.participant.kubernetes.helm.PodStatusValidator;
40 import org.onap.policy.clamp.controlloop.participant.kubernetes.models.ChartInfo;
41 import org.onap.policy.clamp.controlloop.participant.kubernetes.service.ChartService;
42 import org.onap.policy.common.utils.coder.Coder;
43 import org.onap.policy.common.utils.coder.CoderException;
44 import org.onap.policy.common.utils.coder.StandardCoder;
45 import org.onap.policy.models.base.PfModelException;
46 import org.onap.policy.models.tosca.authorative.concepts.ToscaNodeTemplate;
47 import org.onap.policy.models.tosca.authorative.concepts.ToscaServiceTemplate;
48 import org.slf4j.Logger;
49 import org.slf4j.LoggerFactory;
50 import org.springframework.beans.factory.annotation.Autowired;
51 import org.springframework.stereotype.Component;
52
53
54 /**
55  * This class handles implementation of controlLoopElement updates.
56  */
57 @Component
58 public class ControlLoopElementHandler implements ControlLoopElementListener {
59     private static final Logger LOGGER = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
60
61     // Map of helm installation and the status of corresponding pods
62     @Getter
63     private static Map<String, Map<String, String>> podStatusMap = new ConcurrentHashMap<>();
64     private static final Coder CODER = new StandardCoder();
65
66     @Autowired
67     private ChartService chartService;
68
69     @Setter
70     private ParticipantIntermediaryApi intermediaryApi;
71
72     // Map of CLElement Id and installed Helm charts
73     @Getter(AccessLevel.PACKAGE)
74     private final Map<UUID, ChartInfo> chartMap = new HashMap<>();
75
76     // Default thread config values
77     private static class ThreadConfig {
78         private int uninitializedToPassiveTimeout = 60;
79         private int podStatusCheckInterval = 30;
80     }
81
82     /**
83      * Callback method to handle a control loop element state change.
84      *
85      * @param controlLoopElementId the ID of the control loop element
86      * @param currentState the current state of the control loop element
87      * @param newState the state to which the control loop element is changing to
88      */
89     @Override
90     public synchronized void controlLoopElementStateChange(UUID controlLoopElementId, ControlLoopState currentState,
91                                                            ControlLoopOrderedState newState) {
92         switch (newState) {
93             case UNINITIALISED:
94                 ChartInfo chart = chartMap.get(controlLoopElementId);
95                 if (chart != null) {
96                     LOGGER.info("Helm deployment to be deleted {} ", chart.getReleaseName());
97                     try {
98                         chartService.uninstallChart(chart);
99                         intermediaryApi.updateControlLoopElementState(controlLoopElementId, newState,
100                             ControlLoopState.UNINITIALISED);
101                         chartMap.remove(controlLoopElementId);
102                         podStatusMap.remove(chart.getReleaseName());
103                     } catch (ServiceException se) {
104                         LOGGER.warn("deletion of Helm deployment failed", se);
105                     }
106                 }
107                 break;
108             case PASSIVE:
109                 intermediaryApi.updateControlLoopElementState(controlLoopElementId, newState, ControlLoopState.PASSIVE);
110                 break;
111             case RUNNING:
112                 intermediaryApi.updateControlLoopElementState(controlLoopElementId, newState, ControlLoopState.RUNNING);
113                 break;
114             default:
115                 LOGGER.warn("cannot transition from state {} to state {}", currentState, newState);
116                 break;
117         }
118     }
119
120
121     /**
122      * Callback method to handle an update on a control loop element.
123      *
124      * @param element the information on the control loop element
125      * @param controlLoopDefinition toscaServiceTemplate
126      * @throws PfModelException in case of an exception
127      */
128     @Override
129     public synchronized void controlLoopElementUpdate(ControlLoopElement element,
130                                                       ToscaServiceTemplate controlLoopDefinition)
131         throws PfModelException {
132
133         for (Map.Entry<String, ToscaNodeTemplate> nodeTemplate : controlLoopDefinition.getToscaTopologyTemplate()
134             .getNodeTemplates().entrySet()) {
135
136             // Fetching the node template of corresponding CL element
137             if (element.getDefinition().getName().equals(nodeTemplate.getKey())
138                 && nodeTemplate.getValue().getProperties().containsKey("chart")) {
139                 @SuppressWarnings("unchecked")
140                 Map<String, Object> chartData =
141                     (Map<String, Object>) nodeTemplate.getValue().getProperties().get("chart");
142
143                 LOGGER.info("Installation request received for the Helm Chart {} ", chartData);
144                 try {
145                     var chartInfo =  CODER.decode(String.valueOf(chartData), ChartInfo.class);
146                     var repositoryValue = chartData.get("repository");
147                     if (repositoryValue != null) {
148                         chartInfo.setRepository(repositoryValue.toString());
149                     }
150                     chartService.installChart(chartInfo);
151                     chartMap.put(element.getId(), chartInfo);
152
153                     var config = CODER.convert(nodeTemplate.getValue().getProperties(), ThreadConfig.class);
154                     checkPodStatus(chartInfo, config.uninitializedToPassiveTimeout, config.podStatusCheckInterval);
155
156                 } catch (ServiceException | CoderException | IOException e) {
157                     LOGGER.warn("Installation of Helm chart failed", e);
158                 }
159             }
160         }
161     }
162
163     /**
164      * Invoke a new thread to check the status of deployed pods.
165      * @param chart ChartInfo
166      */
167     public void checkPodStatus(ChartInfo chart, int timeout, int podStatusCheckInterval) {
168         // Invoke runnable thread to check pod status
169         var runnableThread = new Thread(new PodStatusValidator(chart, timeout, podStatusCheckInterval));
170         runnableThread.start();
171     }
172
173     /**
174      * Overridden method.
175      *
176      * @param controlLoopElementId controlLoopElement id
177      * @throws PfModelException incase of error
178      */
179     @Override
180     public synchronized void handleStatistics(UUID controlLoopElementId) throws PfModelException {
181         // TODO Implement statistics functionality
182     }
183 }