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