b4cca3acfe65fc80eeaff4e851ce0f040994325b
[policy/clamp.git] /
1 /*-
2  * ============LICENSE_START=======================================================
3  *  Copyright (C) 2021-2022 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.time.Instant;
26 import java.util.HashMap;
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 java.util.concurrent.Future;
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.AcElementStatistics;
44 import org.onap.policy.clamp.models.acm.concepts.AutomationCompositionElement;
45 import org.onap.policy.clamp.models.acm.concepts.AutomationCompositionOrderedState;
46 import org.onap.policy.clamp.models.acm.concepts.AutomationCompositionState;
47 import org.onap.policy.clamp.models.acm.messages.dmaap.participant.ParticipantMessageType;
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.onap.policy.models.tosca.authorative.concepts.ToscaConceptIdentifier;
53 import org.onap.policy.models.tosca.authorative.concepts.ToscaNodeTemplate;
54 import org.slf4j.Logger;
55 import org.slf4j.LoggerFactory;
56 import org.springframework.beans.factory.annotation.Autowired;
57 import org.springframework.stereotype.Component;
58
59 /**
60  * This class handles implementation of automationCompositionElement updates.
61  */
62 @Component
63 public class AutomationCompositionElementHandler implements AutomationCompositionElementListener {
64     private static final Logger LOGGER = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
65
66     private ExecutorService executor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
67
68     // Map of helm installation and the status of corresponding pods
69     @Getter
70     private static Map<String, Map<String, String>> podStatusMap = new ConcurrentHashMap<>();
71     private static final Coder CODER = new StandardCoder();
72
73     @Autowired
74     private ChartService chartService;
75
76     @Setter
77     private ParticipantIntermediaryApi intermediaryApi;
78
79     // Map of acElement Id and installed Helm charts
80     @Getter(AccessLevel.PACKAGE)
81     private final Map<UUID, ChartInfo> chartMap = new HashMap<>();
82
83     // Default thread config values
84     private static class ThreadConfig {
85         private int uninitializedToPassiveTimeout = 60;
86         private int podStatusCheckInterval = 30;
87     }
88
89     /**
90      * Callback method to handle a automation composition element state change.
91      *
92      * @param automationCompositionElementId the ID of the automation composition element
93      * @param currentState the current state of the automation composition element
94      * @param newState the state to which the automation composition element is changing to
95      */
96     @Override
97     public synchronized void automationCompositionElementStateChange(ToscaConceptIdentifier automationCompositionId,
98         UUID automationCompositionElementId, AutomationCompositionState currentState,
99         AutomationCompositionOrderedState newState) {
100         switch (newState) {
101             case UNINITIALISED:
102                 ChartInfo chart = chartMap.get(automationCompositionElementId);
103                 if (chart != null) {
104                     LOGGER.info("Helm deployment to be deleted {} ", chart.getReleaseName());
105                     try {
106                         chartService.uninstallChart(chart);
107                         intermediaryApi.updateAutomationCompositionElementState(automationCompositionId,
108                             automationCompositionElementId, newState, AutomationCompositionState.UNINITIALISED,
109                             ParticipantMessageType.AUTOMATION_COMPOSITION_STATE_CHANGE);
110                         chartMap.remove(automationCompositionElementId);
111                         podStatusMap.remove(chart.getReleaseName());
112                     } catch (ServiceException se) {
113                         LOGGER.warn("Deletion of Helm deployment failed", se);
114                     }
115                 }
116                 break;
117             case PASSIVE:
118                 intermediaryApi.updateAutomationCompositionElementState(automationCompositionId,
119                     automationCompositionElementId, newState, AutomationCompositionState.PASSIVE,
120                     ParticipantMessageType.AUTOMATION_COMPOSITION_STATE_CHANGE);
121                 break;
122             case RUNNING:
123                 intermediaryApi.updateAutomationCompositionElementState(automationCompositionId,
124                     automationCompositionElementId, newState, AutomationCompositionState.RUNNING,
125                     ParticipantMessageType.AUTOMATION_COMPOSITION_STATE_CHANGE);
126                 break;
127             default:
128                 LOGGER.warn("Cannot transition from state {} to state {}", currentState, newState);
129                 break;
130         }
131     }
132
133     /**
134      * Callback method to handle an update on a automation composition element.
135      *
136      * @param element the information on the automation composition element
137      * @param nodeTemplate toscaNodeTemplate
138      * @throws PfModelException in case of an exception
139      */
140     @Override
141     public synchronized void automationCompositionElementUpdate(ToscaConceptIdentifier automationCompositionId,
142         AutomationCompositionElement element, ToscaNodeTemplate nodeTemplate) throws PfModelException {
143         @SuppressWarnings("unchecked")
144         Map<String, Object> chartData = (Map<String, Object>) nodeTemplate.getProperties().get("chart");
145
146         LOGGER.info("Installation request received for the Helm Chart {} ", chartData);
147         try {
148             var chartInfo = CODER.convert(chartData, ChartInfo.class);
149             if (chartService.installChart(chartInfo)) {
150                 chartMap.put(element.getId(), chartInfo);
151
152                 var config = CODER.convert(nodeTemplate.getProperties(),
153                         ThreadConfig.class);
154                 checkPodStatus(automationCompositionId, element.getId(), chartInfo,
155                         config.uninitializedToPassiveTimeout, config.podStatusCheckInterval);
156             }
157         } catch (ServiceException | CoderException | IOException | ExecutionException
158                 | InterruptedException e) {
159             LOGGER.warn("Installation of Helm chart failed", e);
160         }
161     }
162
163     /**
164      * Invoke a new thread to check the status of deployed pods.
165      *
166      * @param chart ChartInfo
167      */
168     public void checkPodStatus(ToscaConceptIdentifier controlLoopId, UUID elementId,
169             ChartInfo chart, int timeout, int podStatusCheckInterval) throws ExecutionException, InterruptedException {
170         // Invoke runnable thread to check pod status
171         Future<String> result = executor.submit(new PodStatusValidator(chart, timeout,
172                 podStatusCheckInterval), "Done");
173         if (!result.get().isEmpty()) {
174             LOGGER.info("Pod Status Validator Completed: {}", result.isDone());
175             intermediaryApi.updateAutomationCompositionElementState(controlLoopId, elementId,
176                 AutomationCompositionOrderedState.PASSIVE, AutomationCompositionState.PASSIVE,
177                 ParticipantMessageType.AUTOMATION_COMPOSITION_STATE_CHANGE);
178         }
179     }
180
181     /**
182      * Overridden method.
183      *
184      * @param automationCompositionElementId automationCompositionElement id
185      * @throws PfModelException in case of error
186      */
187     @Override
188     public synchronized void handleStatistics(UUID automationCompositionElementId) throws PfModelException {
189         var acElement = intermediaryApi.getAutomationCompositionElement(automationCompositionElementId);
190         if (acElement != null) {
191             var acElementStatistics = new AcElementStatistics();
192             acElementStatistics.setState(acElement.getState());
193             acElementStatistics.setTimeStamp(Instant.now());
194             intermediaryApi.updateAutomationCompositionElementStatistics(automationCompositionElementId,
195                 acElementStatistics);
196         }
197     }
198 }