a8a74625425a711da6af07dd1cfad8712b0528b9
[policy/clamp.git] /
1 /*-
2  * ============LICENSE_START=======================================================
3  *  Copyright (C) 2021-2022 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 import java.io.IOException;
24 import java.lang.invoke.MethodHandles;
25 import java.time.Instant;
26 import java.util.HashMap;
27 import java.util.Map;
28 import java.util.UUID;
29 import java.util.concurrent.ConcurrentHashMap;
30 import java.util.concurrent.ExecutionException;
31 import java.util.concurrent.ExecutorService;
32 import java.util.concurrent.Executors;
33 import java.util.concurrent.Future;
34 import lombok.AccessLevel;
35 import lombok.Getter;
36 import lombok.Setter;
37 import org.onap.policy.clamp.controlloop.models.controlloop.concepts.ClElementStatistics;
38 import org.onap.policy.clamp.controlloop.models.controlloop.concepts.ControlLoopElement;
39 import org.onap.policy.clamp.controlloop.models.controlloop.concepts.ControlLoopOrderedState;
40 import org.onap.policy.clamp.controlloop.models.controlloop.concepts.ControlLoopState;
41 import org.onap.policy.clamp.controlloop.models.messages.dmaap.participant.ParticipantMessageType;
42 import org.onap.policy.clamp.controlloop.participant.intermediary.api.ControlLoopElementListener;
43 import org.onap.policy.clamp.controlloop.participant.intermediary.api.ParticipantIntermediaryApi;
44 import org.onap.policy.clamp.controlloop.participant.kubernetes.exception.ServiceException;
45 import org.onap.policy.clamp.controlloop.participant.kubernetes.helm.PodStatusValidator;
46 import org.onap.policy.clamp.controlloop.participant.kubernetes.models.ChartInfo;
47 import org.onap.policy.clamp.controlloop.participant.kubernetes.service.ChartService;
48 import org.onap.policy.common.utils.coder.Coder;
49 import org.onap.policy.common.utils.coder.CoderException;
50 import org.onap.policy.common.utils.coder.StandardCoder;
51 import org.onap.policy.models.base.PfModelException;
52 import org.onap.policy.models.tosca.authorative.concepts.ToscaConceptIdentifier;
53 import org.onap.policy.models.tosca.authorative.concepts.ToscaNodeTemplate;
54 import org.slf4j.Logger;
55 import org.slf4j.LoggerFactory;
56 import org.springframework.beans.factory.annotation.Autowired;
57 import org.springframework.stereotype.Component;
58
59 /**
60  * This class handles implementation of controlLoopElement updates.
61  */
62 @Component
63 public class ControlLoopElementHandler implements ControlLoopElementListener {
64     private static final Logger LOGGER = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
65
66     private ExecutorService executor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
67
68     // Map of helm installation and the status of corresponding pods
69     @Getter
70     private static Map<String, Map<String, String>> podStatusMap = new ConcurrentHashMap<>();
71     private static final Coder CODER = new StandardCoder();
72
73     @Autowired
74     private ChartService chartService;
75
76     @Setter
77     private ParticipantIntermediaryApi intermediaryApi;
78
79     // Map of CLElement Id and installed Helm charts
80     @Getter(AccessLevel.PACKAGE)
81     private final Map<UUID, ChartInfo> chartMap = new HashMap<>();
82
83     // Default thread config values
84     private static class ThreadConfig {
85         private int uninitializedToPassiveTimeout = 60;
86         private int podStatusCheckInterval = 30;
87     }
88
89     /**
90      * Callback method to handle a control loop element state change.
91      *
92      * @param controlLoopElementId the ID of the control loop element
93      * @param currentState the current state of the control loop element
94      * @param newState the state to which the control loop element is changing to
95      */
96     @Override
97     public synchronized void controlLoopElementStateChange(ToscaConceptIdentifier controlLoopId,
98             UUID controlLoopElementId, ControlLoopState currentState, ControlLoopOrderedState newState) {
99         switch (newState) {
100             case UNINITIALISED:
101                 ChartInfo chart = chartMap.get(controlLoopElementId);
102                 if (chart != null) {
103                     LOGGER.info("Helm deployment to be deleted {} ", chart.getReleaseName());
104                     try {
105                         chartService.uninstallChart(chart);
106                         intermediaryApi.updateControlLoopElementState(controlLoopId,
107                             controlLoopElementId, newState, ControlLoopState.UNINITIALISED,
108                             ParticipantMessageType.CONTROL_LOOP_STATE_CHANGE);
109                         chartMap.remove(controlLoopElementId);
110                         podStatusMap.remove(chart.getReleaseName());
111                     } catch (ServiceException se) {
112                         LOGGER.warn("Deletion of Helm deployment failed", se);
113                     }
114                 }
115                 break;
116             case PASSIVE:
117                 intermediaryApi.updateControlLoopElementState(controlLoopId,
118                     controlLoopElementId, newState, ControlLoopState.PASSIVE,
119                     ParticipantMessageType.CONTROL_LOOP_STATE_CHANGE);
120                 break;
121             case RUNNING:
122                 intermediaryApi.updateControlLoopElementState(controlLoopId,
123                     controlLoopElementId, newState, ControlLoopState.RUNNING,
124                     ParticipantMessageType.CONTROL_LOOP_STATE_CHANGE);
125                 break;
126             default:
127                 LOGGER.warn("Cannot transition from state {} to state {}", currentState, newState);
128                 break;
129         }
130     }
131
132
133     /**
134      * Callback method to handle an update on a control loop element.
135      *
136      * @param element the information on the control loop element
137      * @param nodeTemplate toscaNodeTemplate
138      * @throws PfModelException in case of an exception
139      */
140     @Override
141     public synchronized void controlLoopElementUpdate(ToscaConceptIdentifier controlLoopId,
142             ControlLoopElement element, ToscaNodeTemplate nodeTemplate) throws PfModelException {
143         @SuppressWarnings("unchecked")
144         Map<String, Object> chartData =
145             (Map<String, Object>) nodeTemplate.getProperties().get("chart");
146
147         LOGGER.info("Installation request received for the Helm Chart {} ", chartData);
148         try {
149             var chartInfo =  CODER.convert(chartData, ChartInfo.class);
150             chartService.installChart(chartInfo);
151             chartMap.put(element.getId(), chartInfo);
152
153             var config = CODER.convert(nodeTemplate.getProperties(), ThreadConfig.class);
154             checkPodStatus(controlLoopId, element.getId(), chartInfo, config.uninitializedToPassiveTimeout,
155                     config.podStatusCheckInterval);
156
157         } catch (ServiceException | CoderException | IOException | ExecutionException
158                 | InterruptedException e) {
159             LOGGER.warn("Installation of Helm chart failed", e);
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(ToscaConceptIdentifier controlLoopId, UUID elementId,
168             ChartInfo chart, int timeout, int podStatusCheckInterval) throws ExecutionException, InterruptedException {
169         // Invoke runnable thread to check pod status
170         Future<String> result = executor.submit(new PodStatusValidator(chart, timeout,
171                 podStatusCheckInterval), "Done");
172         if (!result.get().isEmpty()) {
173             LOGGER.info("Pod Status Validator Completed: {}", result.isDone());
174             intermediaryApi.updateControlLoopElementState(controlLoopId, elementId,
175                 ControlLoopOrderedState.PASSIVE, ControlLoopState.PASSIVE,
176                 ParticipantMessageType.CONTROL_LOOP_STATE_CHANGE);
177         }
178     }
179
180     /**
181      * Overridden method.
182      *
183      * @param controlLoopElementId controlLoopElement id
184      * @throws PfModelException in case of error
185      */
186     @Override
187     public synchronized void handleStatistics(UUID controlLoopElementId) throws PfModelException {
188         var clElement = intermediaryApi.getControlLoopElement(controlLoopElementId);
189         if (clElement != null) {
190             var clElementStatistics = new ClElementStatistics();
191             clElementStatistics.setControlLoopState(clElement.getState());
192             clElementStatistics.setTimeStamp(Instant.now());
193             intermediaryApi.updateControlLoopElementStatistics(controlLoopElementId, clElementStatistics);
194         }
195     }
196 }