b681ba91d290679773176565bc6cd817ace54313
[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.Map;
27 import java.util.UUID;
28 import java.util.concurrent.ConcurrentHashMap;
29 import java.util.concurrent.ExecutionException;
30 import java.util.concurrent.ExecutorService;
31 import java.util.concurrent.Executors;
32 import javax.ws.rs.core.Response;
33 import lombok.AccessLevel;
34 import lombok.Getter;
35 import lombok.Setter;
36 import net.bytebuddy.implementation.bytecode.Throw;
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.DeployState;
45 import org.onap.policy.clamp.models.acm.concepts.LockState;
46 import org.onap.policy.common.utils.coder.Coder;
47 import org.onap.policy.common.utils.coder.CoderException;
48 import org.onap.policy.common.utils.coder.StandardCoder;
49 import org.onap.policy.models.base.PfModelException;
50 import org.slf4j.Logger;
51 import org.slf4j.LoggerFactory;
52 import org.springframework.beans.factory.annotation.Autowired;
53 import org.springframework.stereotype.Component;
54
55 /**
56  * This class handles implementation of automationCompositionElement updates.
57  */
58 @Component
59 public class AutomationCompositionElementHandler implements AutomationCompositionElementListener {
60     private static final Logger LOGGER = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
61
62     private ExecutorService executor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
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     @Setter
73     private ParticipantIntermediaryApi intermediaryApi;
74
75     // Map of acElement Id and installed Helm charts
76     @Getter(AccessLevel.PACKAGE)
77     private final Map<UUID, ChartInfo> chartMap = new HashMap<>();
78
79     // Default thread config values
80     private static class ThreadConfig {
81         private int uninitializedToPassiveTimeout = 60;
82         private int podStatusCheckInterval = 30;
83     }
84
85     /**
86      * Callback method to handle a automation composition element state change.
87      *
88      * @param automationCompositionElementId the ID of the automation composition element
89      */
90     @Override
91     public synchronized void undeploy(UUID automationCompositionId, UUID automationCompositionElementId) {
92         var chart = chartMap.get(automationCompositionElementId);
93         if (chart != null) {
94             LOGGER.info("Helm deployment to be deleted {} ", chart.getReleaseName());
95             try {
96                 chartService.uninstallChart(chart);
97                 intermediaryApi.updateAutomationCompositionElementState(automationCompositionId,
98                         automationCompositionElementId, DeployState.UNDEPLOYED, LockState.NONE);
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         @SuppressWarnings("unchecked")
119         var chartData = (Map<String, Object>) properties.get("chart");
120
121         LOGGER.info("Installation request received for the Helm Chart {} ", chartData);
122         try {
123             var chartInfo = CODER.convert(chartData, ChartInfo.class);
124             if (chartService.installChart(chartInfo)) {
125                 chartMap.put(element.getId(), chartInfo);
126
127                 var config = CODER.convert(properties, ThreadConfig.class);
128                 checkPodStatus(automationCompositionId, element.getId(), chartInfo,
129                         config.uninitializedToPassiveTimeout, config.podStatusCheckInterval);
130             }
131         } catch (ServiceException | CoderException | IOException e) {
132             LOGGER.warn("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 (ExecutionException e) {
137             throw new PfModelException(Response.Status.BAD_REQUEST, "Error retrieving pod status result ", e);
138         }
139     }
140
141     /**
142      * Invoke a new thread to check the status of deployed pods.
143      *
144      * @param chart ChartInfo
145      */
146     public void checkPodStatus(UUID automationCompositionId, UUID elementId, ChartInfo chart, int timeout,
147             int podStatusCheckInterval) throws ExecutionException, InterruptedException {
148         // Invoke runnable thread to check pod status
149         var result = executor.submit(new PodStatusValidator(chart, timeout, podStatusCheckInterval), "Done");
150         if (!result.get().isEmpty()) {
151             LOGGER.info("Pod Status Validator Completed: {}", result.isDone());
152             intermediaryApi.updateAutomationCompositionElementState(automationCompositionId, elementId,
153                     DeployState.DEPLOYED, LockState.LOCKED);
154         }
155     }
156 }