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