8aa74f30fe81d9db377a1450c5747f33c942c03d
[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.slf4j.Logger;
48 import org.slf4j.LoggerFactory;
49 import org.springframework.beans.factory.annotation.Autowired;
50 import org.springframework.stereotype.Component;
51
52
53 /**
54  * This class handles implementation of controlLoopElement updates.
55  */
56 @Component
57 public class ControlLoopElementHandler implements ControlLoopElementListener {
58     private static final Logger LOGGER = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
59
60     // Map of helm installation and the status of corresponding pods
61     @Getter
62     private static Map<String, Map<String, String>> podStatusMap = new ConcurrentHashMap<>();
63     private static final Coder CODER = new StandardCoder();
64
65     @Autowired
66     private ChartService chartService;
67
68     @Setter
69     private ParticipantIntermediaryApi intermediaryApi;
70
71     // Map of CLElement Id and installed Helm charts
72     @Getter(AccessLevel.PACKAGE)
73     private final Map<UUID, ChartInfo> chartMap = new HashMap<>();
74
75     // Default thread config values
76     private static class ThreadConfig {
77         private int uninitializedToPassiveTimeout = 60;
78         private int podStatusCheckInterval = 30;
79     }
80
81     /**
82      * Callback method to handle a control loop element state change.
83      *
84      * @param controlLoopElementId the ID of the control loop element
85      * @param currentState the current state of the control loop element
86      * @param newState the state to which the control loop element is changing to
87      */
88     @Override
89     public synchronized void controlLoopElementStateChange(UUID controlLoopElementId, ControlLoopState currentState,
90                                                            ControlLoopOrderedState newState) {
91         switch (newState) {
92             case UNINITIALISED:
93                 ChartInfo chart = chartMap.get(controlLoopElementId);
94                 if (chart != null) {
95                     LOGGER.info("Helm deployment to be deleted {} ", chart.getReleaseName());
96                     try {
97                         chartService.uninstallChart(chart);
98                         intermediaryApi.updateControlLoopElementState(controlLoopElementId, newState,
99                             ControlLoopState.UNINITIALISED);
100                         chartMap.remove(controlLoopElementId);
101                         podStatusMap.remove(chart.getReleaseName());
102                     } catch (ServiceException se) {
103                         LOGGER.warn("deletion of Helm deployment failed", se);
104                     }
105                 }
106                 break;
107             case PASSIVE:
108                 intermediaryApi.updateControlLoopElementState(controlLoopElementId, newState, ControlLoopState.PASSIVE);
109                 break;
110             case RUNNING:
111                 intermediaryApi.updateControlLoopElementState(controlLoopElementId, newState, ControlLoopState.RUNNING);
112                 break;
113             default:
114                 LOGGER.warn("cannot transition from state {} to state {}", currentState, newState);
115                 break;
116         }
117     }
118
119
120     /**
121      * Callback method to handle an update on a control loop element.
122      *
123      * @param element the information on the control loop element
124      * @param nodeTemplate toscaNodeTemplate
125      * @throws PfModelException in case of an exception
126      */
127     @Override
128     public synchronized void controlLoopElementUpdate(ControlLoopElement element,
129             ToscaNodeTemplate nodeTemplate) throws PfModelException {
130         @SuppressWarnings("unchecked")
131         Map<String, Object> chartData =
132             (Map<String, Object>) nodeTemplate.getProperties().get("chart");
133
134         LOGGER.info("Installation request received for the Helm Chart {} ", chartData);
135         try {
136             var chartInfo =  CODER.convert(chartData, ChartInfo.class);
137             chartService.installChart(chartInfo);
138             chartMap.put(element.getId(), chartInfo);
139
140             var config = CODER.convert(nodeTemplate.getProperties(), ThreadConfig.class);
141             checkPodStatus(chartInfo, config.uninitializedToPassiveTimeout, config.podStatusCheckInterval);
142
143         } catch (ServiceException | CoderException | IOException e) {
144             LOGGER.warn("Installation of Helm chart failed", e);
145         }
146     }
147
148     /**
149      * Invoke a new thread to check the status of deployed pods.
150      * @param chart ChartInfo
151      */
152     public void checkPodStatus(ChartInfo chart, int timeout, int podStatusCheckInterval) {
153         // Invoke runnable thread to check pod status
154         var runnableThread = new Thread(new PodStatusValidator(chart, timeout, podStatusCheckInterval));
155         runnableThread.start();
156     }
157
158     /**
159      * Overridden method.
160      *
161      * @param controlLoopElementId controlLoopElement id
162      * @throws PfModelException incase of error
163      */
164     @Override
165     public synchronized void handleStatistics(UUID controlLoopElementId) throws PfModelException {
166         // TODO Implement statistics functionality
167     }
168 }