1c40c72814c2da753aa5bdc91ec57c029deaf628
[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.Map;
29 import java.util.UUID;
30 import java.util.concurrent.ConcurrentHashMap;
31 import lombok.AccessLevel;
32 import lombok.Getter;
33 import org.onap.policy.clamp.acm.participant.intermediary.api.ParticipantIntermediaryApi;
34 import org.onap.policy.clamp.acm.participant.intermediary.api.impl.AcElementListenerV1;
35 import org.onap.policy.clamp.acm.participant.kubernetes.exception.ServiceException;
36 import org.onap.policy.clamp.acm.participant.kubernetes.helm.PodStatusValidator;
37 import org.onap.policy.clamp.acm.participant.kubernetes.models.ChartInfo;
38 import org.onap.policy.clamp.acm.participant.kubernetes.service.ChartService;
39 import org.onap.policy.clamp.common.acm.exception.AutomationCompositionException;
40 import org.onap.policy.clamp.models.acm.concepts.AcElementDeploy;
41 import org.onap.policy.clamp.models.acm.concepts.DeployState;
42 import org.onap.policy.clamp.models.acm.concepts.StateChangeResult;
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.slf4j.Logger;
48 import org.slf4j.LoggerFactory;
49 import org.springframework.beans.factory.annotation.Autowired;
50 import org.springframework.stereotype.Component;
51
52 /**
53  * This class handles implementation of automationCompositionElement updates.
54  */
55 @Component
56 public class AutomationCompositionElementHandler extends AcElementListenerV1 {
57     private static final Logger LOGGER = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
58
59     // Map of helm installation and the status of corresponding pods
60     @Getter
61     private static Map<String, Map<String, String>> podStatusMap = new ConcurrentHashMap<>();
62     private static final Coder CODER = new StandardCoder();
63
64     @Autowired
65     private ChartService chartService;
66
67     // Map of acElement Id and installed Helm charts
68     @Getter(AccessLevel.PACKAGE)
69     private final Map<UUID, ChartInfo> chartMap = new HashMap<>();
70
71     public AutomationCompositionElementHandler(ParticipantIntermediaryApi intermediaryApi) {
72         super(intermediaryApi);
73     }
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 automation composition element state change.
83      *
84      * @param automationCompositionElementId the ID of the automation composition element
85      */
86     @Override
87     public synchronized void undeploy(UUID automationCompositionId, UUID automationCompositionElementId) {
88         var chart = chartMap.get(automationCompositionElementId);
89         if (chart != null) {
90             LOGGER.info("Helm deployment to be deleted {} ", chart.getReleaseName());
91             try {
92                 chartService.uninstallChart(chart);
93                 intermediaryApi.updateAutomationCompositionElementState(automationCompositionId,
94                         automationCompositionElementId, DeployState.UNDEPLOYED, null, StateChangeResult.NO_ERROR,
95                         "Undeployed");
96                 chartMap.remove(automationCompositionElementId);
97                 podStatusMap.remove(chart.getReleaseName());
98             } catch (ServiceException se) {
99                 LOGGER.warn("Deletion of Helm deployment failed", se);
100             }
101         }
102     }
103
104     /**
105      * Callback method to handle an update on a automation composition element.
106      *
107      * @param automationCompositionId the automationComposition Id
108      * @param element the information on the automation composition element
109      * @param properties properties Map
110      * @throws PfModelException in case of an exception
111      */
112     @Override
113     public synchronized void deploy(UUID automationCompositionId, AcElementDeploy element,
114             Map<String, Object> properties) throws PfModelException {
115
116         try {
117             var chartInfo = getChartInfo(properties);
118             if (chartService.installChart(chartInfo)) {
119                 chartMap.put(element.getId(), chartInfo);
120
121                 var config = getThreadConfig(properties);
122                 checkPodStatus(automationCompositionId, element.getId(), chartInfo,
123                         config.uninitializedToPassiveTimeout, config.podStatusCheckInterval);
124             } else {
125                 intermediaryApi.updateAutomationCompositionElementState(automationCompositionId, element.getId(),
126                         DeployState.UNDEPLOYED, null, StateChangeResult.FAILED, "Chart not installed");
127             }
128         } catch (ServiceException | IOException e) {
129             throw new PfModelException(Response.Status.BAD_REQUEST, "Installation of Helm chart failed ", e);
130         } catch (InterruptedException e) {
131             Thread.currentThread().interrupt();
132             throw new PfModelException(Response.Status.BAD_REQUEST, "Error invoking ExecutorService ", e);
133         } catch (AutomationCompositionException e) {
134             intermediaryApi.updateAutomationCompositionElementState(automationCompositionId, element.getId(),
135                     DeployState.UNDEPLOYED, null, StateChangeResult.FAILED, e.getMessage());
136         }
137     }
138
139     private ThreadConfig getThreadConfig(Map<String, Object> properties) throws AutomationCompositionException {
140         try {
141             return CODER.convert(properties, ThreadConfig.class);
142         } catch (CoderException e) {
143             throw new AutomationCompositionException(Status.BAD_REQUEST, "Error extracting ThreadConfig ", e);
144         }
145     }
146
147     private ChartInfo getChartInfo(Map<String, Object> properties) throws AutomationCompositionException {
148         @SuppressWarnings("unchecked")
149         var chartData = (Map<String, Object>) properties.get("chart");
150
151         LOGGER.info("Installation request received for the Helm Chart {} ", chartData);
152         try {
153             return CODER.convert(chartData, ChartInfo.class);
154         } catch (CoderException e) {
155             throw new AutomationCompositionException(Status.BAD_REQUEST, "Error extracting ChartInfo ", e);
156         }
157     }
158
159     /**
160      * Invoke a new thread to check the status of deployed pods.
161      *
162      * @param chart ChartInfo
163      * @throws ServiceException in case of an exception
164      */
165     public void checkPodStatus(UUID automationCompositionId, UUID elementId, ChartInfo chart, int timeout,
166             int podStatusCheckInterval) throws InterruptedException, ServiceException {
167
168         var result = new PodStatusValidator(chart, timeout, podStatusCheckInterval);
169         result.run();
170         LOGGER.info("Pod Status Validator Completed");
171         intermediaryApi.updateAutomationCompositionElementState(automationCompositionId, elementId,
172                 DeployState.DEPLOYED, null, StateChangeResult.NO_ERROR, "Deployed");
173
174     }
175 }