0a14241346c7d757ac31ea5d50c54f5fd9d03113
[policy/clamp.git] /
1 /*-
2  * ========================LICENSE_START=================================
3  * Copyright (C) 2021-2022 Nordix Foundation. All rights reserved.
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  * ========================LICENSE_END===================================
17  */
18
19 package org.onap.policy.clamp.acm.participant.kubernetes.helm;
20
21 import java.io.BufferedReader;
22 import java.io.IOException;
23 import java.io.InputStreamReader;
24 import java.lang.invoke.MethodHandles;
25 import java.nio.charset.StandardCharsets;
26 import java.util.HashMap;
27 import java.util.Map;
28 import org.apache.commons.io.IOUtils;
29 import org.apache.commons.lang3.StringUtils;
30 import org.onap.policy.clamp.acm.participant.kubernetes.exception.ServiceException;
31 import org.onap.policy.clamp.acm.participant.kubernetes.handler.AutomationCompositionElementHandler;
32 import org.onap.policy.clamp.acm.participant.kubernetes.models.ChartInfo;
33 import org.slf4j.Logger;
34 import org.slf4j.LoggerFactory;
35
36
37 public class PodStatusValidator {
38
39     private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
40
41     private final int statusCheckInterval;
42
43     //Timeout for the thread to exit.
44     private final int timeout;
45
46     private ChartInfo chart;
47
48     private HelmClient client = new HelmClient();
49
50     /**
51      * Constructor for PodStatusValidator.
52      *
53      * @param chart chartInfo
54      * @param timeout timeout for the thread to exit
55      * @param statusCheckInterval Interval to check pod status
56      */
57     public PodStatusValidator(ChartInfo chart, int timeout, int statusCheckInterval) {
58         this.chart = chart;
59         this.timeout = timeout;
60         this.statusCheckInterval = statusCheckInterval;
61     }
62
63     /**
64      * Run the execution.
65      *
66      * @throws InterruptedException in case of an exception
67      * @throws ServiceException in case of an exception
68      */
69     public void run() throws InterruptedException, ServiceException {
70         logger.info("Polling the status of deployed pods for the chart {}", chart.getChartId().getName());
71
72         try {
73             verifyPodStatus();
74         } catch (IOException e) {
75             throw new ServiceException("Error verifying the status of the pod. Exiting", e);
76         }
77     }
78
79     private void verifyPodStatus() throws ServiceException, IOException, InterruptedException {
80         var isVerified = false;
81         long endTime = System.currentTimeMillis() + (timeout * 1000L);
82
83         while (!isVerified && System.currentTimeMillis() < endTime) {
84             var output = client.executeCommand(verifyPodStatusCommand(chart));
85             var podStatusMap = mapPodStatus(output);
86             isVerified = !podStatusMap.isEmpty()
87                     && podStatusMap.values().stream().allMatch("Running"::equals);
88             if (!isVerified) {
89                 logger.info("Waiting for the pods to be active for the chart {}", chart.getChartId().getName());
90                 podStatusMap.forEach((key, value) -> logger.info("Pod: {} , state: {}", key, value));
91                 // Recheck status of pods in specific intervals.
92                 Thread.sleep(statusCheckInterval * 1000L);
93             } else {
94                 logger.info("All pods are in running state for the helm chart {}", chart.getChartId().getName());
95                 AutomationCompositionElementHandler.getPodStatusMap().put(chart.getReleaseName(), podStatusMap);
96             }
97         }
98         if (!isVerified) {
99             throw new ServiceException("Time out Exception verifying the status of the pod");
100         }
101     }
102
103     private ProcessBuilder verifyPodStatusCommand(ChartInfo chart) {
104         String cmd = "kubectl get pods --namespace " + chart.getNamespace() + " | grep " + getPodName();
105         return new ProcessBuilder("sh", "-c", cmd);
106     }
107
108     private String getPodName() {
109         return StringUtils.isNotEmpty(chart.getPodName()) ? chart.getPodName() : chart.getChartId().getName();
110     }
111
112     private Map<String, String> mapPodStatus(String output) throws IOException {
113         Map<String, String> podStatusMap = new HashMap<>();
114         var podName = getPodName();
115         try (var reader = new BufferedReader(new InputStreamReader(IOUtils.toInputStream(output,
116             StandardCharsets.UTF_8)))) {
117             var line = reader.readLine();
118             while (line != null) {
119                 if (line.contains(podName)) {
120                     var result = line.split("\\s+");
121                     podStatusMap.put(result[0], result[2]);
122                 }
123                 line = reader.readLine();
124             }
125         }
126         if (podStatusMap.isEmpty()) {
127             logger.warn("Status of  Pod {} is empty", podName);
128         }
129         return podStatusMap;
130     }
131 }