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