ae8e47461de70e38d440c96a9cb60b69c4895711
[policy/clamp.git] /
1 /*-
2  * ============LICENSE_START=======================================================
3  *  Copyright (C) 2021-2024 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.acm.participant.kubernetes.handler;
22
23 import jakarta.ws.rs.core.Response;
24 import jakarta.ws.rs.core.Response.Status;
25 import java.io.IOException;
26 import java.lang.invoke.MethodHandles;
27 import java.util.HashMap;
28 import java.util.List;
29 import java.util.Map;
30 import java.util.UUID;
31 import java.util.concurrent.ConcurrentHashMap;
32 import lombok.AccessLevel;
33 import lombok.Getter;
34 import org.onap.policy.clamp.acm.participant.intermediary.api.ParticipantIntermediaryApi;
35 import org.onap.policy.clamp.acm.participant.intermediary.api.impl.AcElementListenerV1;
36 import org.onap.policy.clamp.acm.participant.kubernetes.exception.ServiceException;
37 import org.onap.policy.clamp.acm.participant.kubernetes.helm.PodStatusValidator;
38 import org.onap.policy.clamp.acm.participant.kubernetes.models.ChartInfo;
39 import org.onap.policy.clamp.acm.participant.kubernetes.service.ChartService;
40 import org.onap.policy.clamp.common.acm.exception.AutomationCompositionException;
41 import org.onap.policy.clamp.models.acm.concepts.AcElementDeploy;
42 import org.onap.policy.clamp.models.acm.concepts.AcTypeState;
43 import org.onap.policy.clamp.models.acm.concepts.AutomationCompositionElementDefinition;
44 import org.onap.policy.clamp.models.acm.concepts.DeployState;
45 import org.onap.policy.clamp.models.acm.concepts.LockState;
46 import org.onap.policy.clamp.models.acm.concepts.StateChangeResult;
47 import org.onap.policy.clamp.models.acm.utils.AcmUtils;
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.slf4j.Logger;
53 import org.slf4j.LoggerFactory;
54 import org.springframework.beans.factory.annotation.Autowired;
55 import org.springframework.stereotype.Component;
56
57 /**
58  * This class handles implementation of automationCompositionElement updates.
59  */
60 @Component
61 public class AutomationCompositionElementHandler extends AcElementListenerV1 {
62     private static final Logger LOGGER = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
63
64     // Map of helm installation and the status of corresponding pods
65     @Getter
66     private static Map<String, Map<String, String>> podStatusMap = new ConcurrentHashMap<>();
67     private static final Coder CODER = new StandardCoder();
68
69     @Autowired
70     private ChartService chartService;
71
72     // Map of acElement Id and installed Helm charts
73     @Getter(AccessLevel.PACKAGE)
74     private final Map<UUID, ChartInfo> chartMap = new HashMap<>();
75
76     public AutomationCompositionElementHandler(ParticipantIntermediaryApi intermediaryApi) {
77         super(intermediaryApi);
78     }
79
80     // Default thread config values
81     private static class ThreadConfig {
82         private int uninitializedToPassiveTimeout = 60;
83         private int podStatusCheckInterval = 30;
84     }
85
86     /**
87      * Callback method to handle a automation composition element state change.
88      *
89      * @param automationCompositionElementId the ID of the automation composition element
90      */
91     @Override
92     public synchronized void undeploy(UUID automationCompositionId, UUID automationCompositionElementId) {
93         var chart = chartMap.get(automationCompositionElementId);
94         if (chart != null) {
95             LOGGER.info("Helm deployment to be deleted {} ", chart.getReleaseName());
96             try {
97                 chartService.uninstallChart(chart);
98                 intermediaryApi.updateAutomationCompositionElementState(automationCompositionId,
99                         automationCompositionElementId, DeployState.UNDEPLOYED, null, StateChangeResult.NO_ERROR,
100                         "Undeployed");
101                 chartMap.remove(automationCompositionElementId);
102                 podStatusMap.remove(chart.getReleaseName());
103             } catch (ServiceException se) {
104                 LOGGER.warn("Deletion of Helm deployment failed", se);
105             }
106         }
107     }
108
109     /**
110      * Callback method to handle an update on a automation composition element.
111      *
112      * @param automationCompositionId the automationComposition Id
113      * @param element the information on the automation composition element
114      * @param properties properties Map
115      * @throws PfModelException in case of an exception
116      */
117     @Override
118     public synchronized void deploy(UUID automationCompositionId, AcElementDeploy element,
119             Map<String, Object> properties) throws PfModelException {
120
121         try {
122             var chartInfo = getChartInfo(properties);
123             if (chartService.installChart(chartInfo)) {
124                 chartMap.put(element.getId(), chartInfo);
125
126                 var config = getThreadConfig(properties);
127                 checkPodStatus(automationCompositionId, element.getId(), chartInfo,
128                         config.uninitializedToPassiveTimeout, config.podStatusCheckInterval);
129             } else {
130                 intermediaryApi.updateAutomationCompositionElementState(automationCompositionId, element.getId(),
131                         DeployState.UNDEPLOYED, null, StateChangeResult.FAILED, "Chart not installed");
132             }
133         } catch (ServiceException | IOException e) {
134             throw new PfModelException(Response.Status.BAD_REQUEST, "Installation of Helm chart failed ", e);
135         } catch (InterruptedException e) {
136             Thread.currentThread().interrupt();
137             throw new PfModelException(Response.Status.BAD_REQUEST, "Error invoking ExecutorService ", e);
138         } catch (AutomationCompositionException e) {
139             intermediaryApi.updateAutomationCompositionElementState(automationCompositionId, element.getId(),
140                     DeployState.UNDEPLOYED, null, StateChangeResult.FAILED, e.getMessage());
141         }
142     }
143
144     private ThreadConfig getThreadConfig(Map<String, Object> properties) throws AutomationCompositionException {
145         try {
146             return CODER.convert(properties, ThreadConfig.class);
147         } catch (CoderException e) {
148             throw new AutomationCompositionException(Status.BAD_REQUEST, "Error extracting ThreadConfig ", e);
149         }
150     }
151
152     private ChartInfo getChartInfo(Map<String, Object> properties) throws AutomationCompositionException {
153         @SuppressWarnings("unchecked")
154         var chartData = (Map<String, Object>) properties.get("chart");
155
156         LOGGER.info("Installation request received for the Helm Chart {} ", chartData);
157         try {
158             return CODER.convert(chartData, ChartInfo.class);
159         } catch (CoderException e) {
160             throw new AutomationCompositionException(Status.BAD_REQUEST, "Error extracting ChartInfo ", e);
161         }
162     }
163
164     /**
165      * Invoke a new thread to check the status of deployed pods.
166      *
167      * @param chart ChartInfo
168      * @throws ServiceException in case of an exception
169      */
170     public void checkPodStatus(UUID automationCompositionId, UUID elementId, ChartInfo chart, int timeout,
171             int podStatusCheckInterval) throws InterruptedException, ServiceException {
172
173         var result = new PodStatusValidator(chart, timeout, podStatusCheckInterval);
174         result.run();
175         LOGGER.info("Pod Status Validator Completed");
176         intermediaryApi.updateAutomationCompositionElementState(automationCompositionId, elementId,
177                 DeployState.DEPLOYED, null, StateChangeResult.NO_ERROR, "Deployed");
178
179     }
180
181     @Override
182     public void lock(UUID instanceId, UUID elementId) throws PfModelException {
183         intermediaryApi.updateAutomationCompositionElementState(instanceId, elementId, null, LockState.LOCKED,
184                 StateChangeResult.NO_ERROR, "Locked");
185     }
186
187     @Override
188     public void unlock(UUID instanceId, UUID elementId) throws PfModelException {
189         intermediaryApi.updateAutomationCompositionElementState(instanceId, elementId, null, LockState.UNLOCKED,
190                 StateChangeResult.NO_ERROR, "Unlocked");
191     }
192
193     @Override
194     public void delete(UUID instanceId, UUID elementId) throws PfModelException {
195         intermediaryApi.updateAutomationCompositionElementState(instanceId, elementId, DeployState.DELETED, null,
196                 StateChangeResult.NO_ERROR, "Deleted");
197     }
198
199     @Override
200     public void update(UUID instanceId, AcElementDeploy element, Map<String, Object> properties)
201             throws PfModelException {
202         intermediaryApi.updateAutomationCompositionElementState(instanceId, element.getId(), DeployState.DEPLOYED, null,
203                 StateChangeResult.NO_ERROR, "Update not supported");
204     }
205
206     @Override
207     public void prime(UUID compositionId, List<AutomationCompositionElementDefinition> elementDefinitionList)
208             throws PfModelException {
209         intermediaryApi.updateCompositionState(compositionId, AcTypeState.PRIMED, StateChangeResult.NO_ERROR, "Primed");
210     }
211
212     @Override
213     public void deprime(UUID compositionId) throws PfModelException {
214         intermediaryApi.updateCompositionState(compositionId, AcTypeState.COMMISSIONED, StateChangeResult.NO_ERROR,
215                 "Deprimed");
216     }
217
218     @Override
219     public void handleRestartComposition(UUID compositionId,
220             List<AutomationCompositionElementDefinition> elementDefinitionList, AcTypeState state)
221             throws PfModelException {
222         var finalState = AcTypeState.PRIMED.equals(state) || AcTypeState.PRIMING.equals(state) ? AcTypeState.PRIMED
223                 : AcTypeState.COMMISSIONED;
224         intermediaryApi.updateCompositionState(compositionId, finalState, StateChangeResult.NO_ERROR, "Restarted");
225     }
226
227     @Override
228     public void handleRestartInstance(UUID automationCompositionId, AcElementDeploy element,
229             Map<String, Object> properties, DeployState deployState, LockState lockState) throws PfModelException {
230         if (DeployState.DEPLOYING.equals(deployState)) {
231             deploy(automationCompositionId, element, properties);
232             return;
233         }
234         if (DeployState.UNDEPLOYING.equals(deployState) || DeployState.DEPLOYED.equals(deployState)
235                 || DeployState.UPDATING.equals(deployState)) {
236             try {
237                 var chartInfo = getChartInfo(properties);
238                 chartMap.put(element.getId(), chartInfo);
239             } catch (AutomationCompositionException e) {
240                 intermediaryApi.updateAutomationCompositionElementState(automationCompositionId, element.getId(),
241                         DeployState.UNDEPLOYED, null, StateChangeResult.FAILED, e.getMessage());
242             }
243         }
244         if (DeployState.UNDEPLOYING.equals(deployState)) {
245             undeploy(automationCompositionId, element.getId());
246             return;
247         }
248         deployState = AcmUtils.deployCompleted(deployState);
249         lockState = AcmUtils.lockCompleted(deployState, lockState);
250         intermediaryApi.updateAutomationCompositionElementState(automationCompositionId, element.getId(), deployState,
251                 lockState, StateChangeResult.NO_ERROR, "Restarted");
252     }
253 }