f8b08a6be19338dadecb6d99fe4ed0fd60e32d4f
[policy/clamp.git] /
1 /*-
2  * ========================LICENSE_START=================================
3  * Copyright (C) 2021 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 lombok.SneakyThrows;
29 import org.apache.commons.io.IOUtils;
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 implements Runnable {
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     /**
49      * Constructor for PodStatusValidator.
50      * @param chart chartInfo
51      * @param timeout timeout for the thread to exit
52      * @param statusCheckInterval Interval to check pod status
53      */
54     public PodStatusValidator(ChartInfo chart, int timeout, int statusCheckInterval) {
55         this.chart = chart;
56         this.timeout = timeout;
57         this.statusCheckInterval = statusCheckInterval;
58     }
59
60
61     @SneakyThrows
62     @Override
63     public void run() {
64         logger.info("Polling the status of deployed pods for the chart {}", chart.getChartId().getName());
65         Map<String, String> podStatusMap;
66         String output = null;
67         var isVerified = false;
68         long endTime = System.currentTimeMillis() + (timeout * 1000L);
69
70         while (!isVerified && System.currentTimeMillis() < endTime) {
71             try {
72                 output = HelmClient.executeCommand(verifyPodStatusCommand(chart));
73                 podStatusMap = mapPodStatus(output);
74                 isVerified = podStatusMap.values()
75                     .stream()
76                     .allMatch("Running"::equals);
77                 if (! isVerified) {
78                     logger.info("Waiting for the pods to be active for the chart {}", chart.getChartId().getName());
79                     podStatusMap.forEach((key, value) -> logger.info("Pod: {} , state: {}", key, value));
80                     AutomationCompositionElementHandler.getPodStatusMap().put(chart.getReleaseName(), podStatusMap);
81                     // Recheck status of pods in specific intervals.
82                     Thread.sleep(statusCheckInterval * 1000L);
83                 } else {
84                     logger.info("All pods are in running state for the helm chart {}", chart.getChartId().getName());
85                     AutomationCompositionElementHandler.getPodStatusMap().put(chart.getReleaseName(), podStatusMap);
86                 }
87             } catch (ServiceException | IOException  e) {
88                 throw new ServiceException("Error verifying the status of the pod. Exiting", e);
89             }
90         }
91     }
92
93     private ProcessBuilder verifyPodStatusCommand(ChartInfo chart) {
94         String podName = chart.getReleaseName() + "-" + chart.getChartId().getName();
95         String cmd = "kubectl get pods --namespace " +  chart.getNamespace() + " | grep " + podName;
96         return new ProcessBuilder("sh", "-c", cmd);
97     }
98
99
100     private Map<String, String> mapPodStatus(String output) throws IOException, ServiceException {
101         Map<String, String> podStatusMap = new HashMap<>();
102         try (var reader = new BufferedReader(new InputStreamReader(IOUtils.toInputStream(output,
103             StandardCharsets.UTF_8)))) {
104             var line = reader.readLine();
105             while (line != null) {
106                 if (line.contains(chart.getChartId().getName())) {
107                     var result = line.split("\\s+");
108                     podStatusMap.put(result[0], result[2]);
109                 }
110                 line = reader.readLine();
111             }
112         }
113         if (!podStatusMap.isEmpty()) {
114             return podStatusMap;
115         } else {
116             throw new ServiceException("Status of Pod is empty");
117         }
118     }
119 }