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