c64bc49069f75e17bb845e126b4d630b45e05d81
[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.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 lombok.AccessLevel;
33 import lombok.Getter;
34 import lombok.Setter;
35 import org.onap.policy.clamp.acm.participant.intermediary.api.AutomationCompositionElementListener;
36 import org.onap.policy.clamp.acm.participant.intermediary.api.ParticipantIntermediaryApi;
37 import org.onap.policy.clamp.acm.participant.kubernetes.exception.ServiceException;
38 import org.onap.policy.clamp.acm.participant.kubernetes.helm.PodStatusValidator;
39 import org.onap.policy.clamp.acm.participant.kubernetes.models.ChartInfo;
40 import org.onap.policy.clamp.acm.participant.kubernetes.service.ChartService;
41 import org.onap.policy.clamp.models.acm.concepts.AutomationCompositionElement;
42 import org.onap.policy.clamp.models.acm.concepts.AutomationCompositionOrderedState;
43 import org.onap.policy.clamp.models.acm.concepts.AutomationCompositionState;
44 import org.onap.policy.clamp.models.acm.messages.dmaap.participant.ParticipantMessageType;
45 import org.onap.policy.common.utils.coder.Coder;
46 import org.onap.policy.common.utils.coder.CoderException;
47 import org.onap.policy.common.utils.coder.StandardCoder;
48 import org.onap.policy.models.base.PfModelException;
49 import org.slf4j.Logger;
50 import org.slf4j.LoggerFactory;
51 import org.springframework.beans.factory.annotation.Autowired;
52 import org.springframework.stereotype.Component;
53
54 /**
55  * This class handles implementation of automationCompositionElement updates.
56  */
57 @Component
58 public class AutomationCompositionElementHandler implements AutomationCompositionElementListener {
59     private static final Logger LOGGER = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
60
61     private ExecutorService executor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
62
63     // Map of helm installation and the status of corresponding pods
64     @Getter
65     private static Map<String, Map<String, String>> podStatusMap = new ConcurrentHashMap<>();
66     private static final Coder CODER = new StandardCoder();
67
68     @Autowired
69     private ChartService chartService;
70
71     @Setter
72     private ParticipantIntermediaryApi intermediaryApi;
73
74     // Map of acElement Id and installed Helm charts
75     @Getter(AccessLevel.PACKAGE)
76     private final Map<UUID, ChartInfo> chartMap = new HashMap<>();
77
78     // Default thread config values
79     private static class ThreadConfig {
80         private int uninitializedToPassiveTimeout = 60;
81         private int podStatusCheckInterval = 30;
82     }
83
84     /**
85      * Callback method to handle a automation composition element state change.
86      *
87      * @param automationCompositionElementId the ID of the automation composition element
88      * @param currentState the current state of the automation composition element
89      * @param newState the state to which the automation composition element is changing to
90      */
91     @Override
92     public synchronized void automationCompositionElementStateChange(UUID automationCompositionId,
93         UUID automationCompositionElementId, AutomationCompositionState currentState,
94         AutomationCompositionOrderedState newState) {
95         switch (newState) {
96             case UNINITIALISED:
97                 var chart = chartMap.get(automationCompositionElementId);
98                 if (chart != null) {
99                     LOGGER.info("Helm deployment to be deleted {} ", chart.getReleaseName());
100                     try {
101                         chartService.uninstallChart(chart);
102                         intermediaryApi.updateAutomationCompositionElementState(automationCompositionId,
103                             automationCompositionElementId, newState, AutomationCompositionState.UNINITIALISED,
104                             ParticipantMessageType.AUTOMATION_COMPOSITION_STATE_CHANGE);
105                         chartMap.remove(automationCompositionElementId);
106                         podStatusMap.remove(chart.getReleaseName());
107                     } catch (ServiceException se) {
108                         LOGGER.warn("Deletion of Helm deployment failed", se);
109                     }
110                 }
111                 break;
112             case PASSIVE:
113                 intermediaryApi.updateAutomationCompositionElementState(automationCompositionId,
114                     automationCompositionElementId, newState, AutomationCompositionState.PASSIVE,
115                     ParticipantMessageType.AUTOMATION_COMPOSITION_STATE_CHANGE);
116                 break;
117             case RUNNING:
118                 intermediaryApi.updateAutomationCompositionElementState(automationCompositionId,
119                     automationCompositionElementId, newState, AutomationCompositionState.RUNNING,
120                     ParticipantMessageType.AUTOMATION_COMPOSITION_STATE_CHANGE);
121                 break;
122             default:
123                 LOGGER.warn("Cannot transition from state {} to state {}", currentState, newState);
124                 break;
125         }
126     }
127
128     /**
129      * Callback method to handle an update on a automation composition element.
130      *
131      * @param automationCompositionId the automationComposition Id
132      * @param element the information on the automation composition element
133      * @param properties properties Map
134      * @throws PfModelException in case of an exception
135      */
136     @Override
137     public synchronized void automationCompositionElementUpdate(UUID automationCompositionId,
138         AutomationCompositionElement element, Map<String, Object> properties) throws PfModelException {
139         @SuppressWarnings("unchecked")
140         var chartData = (Map<String, Object>) properties.get("chart");
141
142         LOGGER.info("Installation request received for the Helm Chart {} ", chartData);
143         try {
144             var chartInfo = CODER.convert(chartData, ChartInfo.class);
145             if (chartService.installChart(chartInfo)) {
146                 chartMap.put(element.getId(), chartInfo);
147
148                 var config = CODER.convert(properties, ThreadConfig.class);
149                 checkPodStatus(automationCompositionId, element.getId(), chartInfo,
150                         config.uninitializedToPassiveTimeout, config.podStatusCheckInterval);
151             }
152         } catch (ServiceException | CoderException | IOException | ExecutionException
153                 | InterruptedException e) {
154             LOGGER.warn("Installation of Helm chart failed", e);
155         }
156     }
157
158     /**
159      * Invoke a new thread to check the status of deployed pods.
160      *
161      * @param chart ChartInfo
162      */
163     public void checkPodStatus(UUID automationCompositionId, UUID elementId,
164             ChartInfo chart, int timeout, int podStatusCheckInterval) throws ExecutionException, InterruptedException {
165         // Invoke runnable thread to check pod status
166         var result = executor.submit(new PodStatusValidator(chart, timeout,
167                 podStatusCheckInterval), "Done");
168         if (!result.get().isEmpty()) {
169             LOGGER.info("Pod Status Validator Completed: {}", result.isDone());
170             intermediaryApi.updateAutomationCompositionElementState(automationCompositionId, elementId,
171                 AutomationCompositionOrderedState.PASSIVE, AutomationCompositionState.PASSIVE,
172                 ParticipantMessageType.AUTOMATION_COMPOSITION_STATE_CHANGE);
173         }
174     }
175 }