b93085e91caac5b9ff13d999176d42aba0c72a98
[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.Map;
28 import java.util.UUID;
29 import org.onap.policy.clamp.acm.participant.intermediary.api.CompositionElementDto;
30 import org.onap.policy.clamp.acm.participant.intermediary.api.InstanceElementDto;
31 import org.onap.policy.clamp.acm.participant.intermediary.api.ParticipantIntermediaryApi;
32 import org.onap.policy.clamp.acm.participant.intermediary.api.impl.AcElementListenerV2;
33 import org.onap.policy.clamp.acm.participant.kubernetes.exception.ServiceException;
34 import org.onap.policy.clamp.acm.participant.kubernetes.helm.PodStatusValidator;
35 import org.onap.policy.clamp.acm.participant.kubernetes.models.ChartInfo;
36 import org.onap.policy.clamp.acm.participant.kubernetes.service.ChartService;
37 import org.onap.policy.clamp.models.acm.concepts.DeployState;
38 import org.onap.policy.clamp.models.acm.concepts.StateChangeResult;
39 import org.onap.policy.common.utils.coder.Coder;
40 import org.onap.policy.common.utils.coder.CoderException;
41 import org.onap.policy.common.utils.coder.StandardCoder;
42 import org.onap.policy.models.base.PfModelException;
43 import org.slf4j.Logger;
44 import org.slf4j.LoggerFactory;
45 import org.springframework.beans.factory.annotation.Autowired;
46 import org.springframework.stereotype.Component;
47
48 /**
49  * This class handles implementation of automationCompositionElement updates.
50  */
51 @Component
52 public class AutomationCompositionElementHandler extends AcElementListenerV2 {
53     private static final Logger LOGGER = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
54
55     private static final Coder CODER = new StandardCoder();
56
57     private final ChartService chartService;
58
59     public AutomationCompositionElementHandler(ParticipantIntermediaryApi intermediaryApi, ChartService chartService) {
60         super(intermediaryApi);
61         this.chartService = chartService;
62     }
63
64
65     // Default thread config values
66     private static class ThreadConfig {
67         private int uninitializedToPassiveTimeout = 60;
68         private int podStatusCheckInterval = 30;
69     }
70
71     /**
72      * Handle an undeploy on a automation composition element.
73      *
74      * @param compositionElement the information of the Automation Composition Definition Element
75      * @param instanceElement    the information of the Automation Composition Instance Element
76      * @throws PfModelException in case of a model exception
77      */
78     @Override
79     public void undeploy(CompositionElementDto compositionElement, InstanceElementDto instanceElement)
80             throws PfModelException {
81
82         var chart = getChartInfo(instanceElement.inProperties());
83         if (chart != null) {
84             LOGGER.info("Helm deployment to be deleted {} ", chart.getReleaseName());
85             try {
86                 chartService.uninstallChart(chart);
87                 intermediaryApi.updateAutomationCompositionElementState(instanceElement.instanceId(),
88                         instanceElement.elementId(), DeployState.UNDEPLOYED, null, StateChangeResult.NO_ERROR,
89                         "Undeployed");
90                 instanceElement.outProperties().remove(chart.getReleaseName());
91                 intermediaryApi.sendAcElementInfo(instanceElement.instanceId(), instanceElement.elementId(),
92                         null, null, instanceElement.outProperties());
93             } catch (ServiceException se) {
94                 throw new PfModelException(Status.EXPECTATION_FAILED, "Deletion of Helm deployment failed", se);
95             }
96         }
97
98     }
99
100     /**
101      * Handle a deploy on a automation composition element.
102      *
103      * @param compositionElement the information of the Automation Composition Definition Element
104      * @param instanceElement    the information of the Automation Composition Instance Element
105      * @throws PfModelException from Policy framework
106      */
107     @Override
108     public void deploy(CompositionElementDto compositionElement, InstanceElementDto instanceElement)
109             throws PfModelException {
110         try {
111             var chartInfo = getChartInfo(instanceElement.inProperties());
112             if (chartService.installChart(chartInfo)) {
113                 var config = getThreadConfig(compositionElement.inProperties());
114                 checkPodStatus(instanceElement.instanceId(), instanceElement.elementId(), chartInfo,
115                         config.uninitializedToPassiveTimeout, config.podStatusCheckInterval, instanceElement);
116             } else {
117                 throw new PfModelException(Response.Status.BAD_REQUEST, "Installation of Helm chart failed ");
118             }
119         } catch (ServiceException | IOException | InterruptedException e) {
120             Thread.currentThread().interrupt();
121             throw new PfModelException(Response.Status.BAD_REQUEST, "Installation of Helm chart failed ", e);
122         }
123
124     }
125
126     private ThreadConfig getThreadConfig(Map<String, Object> properties) throws PfModelException {
127         try {
128             return CODER.convert(properties, ThreadConfig.class);
129         } catch (CoderException e) {
130             throw new PfModelException(Status.BAD_REQUEST, "Error extracting ThreadConfig ", e);
131         }
132     }
133
134     private ChartInfo getChartInfo(Map<String, Object> properties) throws PfModelException {
135         @SuppressWarnings("unchecked")
136         var chartData = (Map<String, Object>) properties.get("chart");
137         LOGGER.info("Installation request received for the Helm Chart {} ", chartData);
138         try {
139             return CODER.convert(chartData, ChartInfo.class);
140         } catch (CoderException e) {
141             throw new PfModelException(Status.BAD_REQUEST, "Error extracting ChartInfo", e);
142         }
143
144     }
145
146     /**
147      * Invoke a new thread to check the status of deployed pods.
148      *
149      * @param chart ChartInfo
150      * @throws PfModelException in case of an exception
151      */
152     public void checkPodStatus(UUID automationCompositionId, UUID elementId, ChartInfo chart, int timeout,
153             int podStatusCheckInterval, InstanceElementDto instanceElement) throws InterruptedException,
154             PfModelException {
155
156         var result = new PodStatusValidator(chart, timeout, podStatusCheckInterval);
157         result.run();
158         LOGGER.info("Pod Status Validator Completed");
159         intermediaryApi.updateAutomationCompositionElementState(automationCompositionId, elementId,
160                 DeployState.DEPLOYED, null, StateChangeResult.NO_ERROR, "Deployed");
161         instanceElement.outProperties().put(chart.getReleaseName(), "Running");
162
163         intermediaryApi.sendAcElementInfo(automationCompositionId, elementId, null, null,
164                 instanceElement.outProperties());
165
166     }
167 }